From da2f03ff736f4c7207cffd84ffe774661416d4c7 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 31 Aug 2021 19:40:32 +0800 Subject: [PATCH] gfx: swapchain refactor (#3751) * gfx: swapchain * acquire/release/surface on swapchain * fix swapchain texture creation * acquire/present back on device * formats are swapchain-specific * swapchain: vk works * enable device agent * format fix * update gfxdef * fix enum decl * pipeline adapt * minor * vk: compress attr locations directly in SPIR-V * gles3 adjust * InputAssembler owns an DrawInfo * gles2 adapt * texture keep track of its hash * device cached states * format * glslang finalize * buffer view adapt * fg: subpass support * minor * 3.4 adapt * profiler adapt * buffer update frequency detection * minor * base commit * swapchain works on metal * spirv * mtltexture issue * remote test code * depthtexture * revert ifdef USE_METAL * ios swapchain header * fix some triple buffer issues * resize accept surface transform Co-authored-by: Zeqiang Li --- native/CMakeLists.txt | 126 +- native/cocos/base/IndexHandle.h | 2 +- native/cocos/base/Macros.h | 14 +- native/cocos/base/Map.h | 7 - native/cocos/base/StringPool.h | 6 +- native/cocos/base/TypeDef.h | 10 +- native/cocos/base/Utils.h | 5 - .../threading/ThreadSafeLinearAllocator.cpp | 2 + native/cocos/bindings/auto/jsb_audio_auto.cpp | 754 ++-- native/cocos/bindings/auto/jsb_audio_auto.h | 46 +- native/cocos/bindings/auto/jsb_cocos_auto.cpp | 306 +- native/cocos/bindings/auto/jsb_cocos_auto.h | 16 +- .../bindings/auto/jsb_dragonbones_auto.cpp | 134 +- .../bindings/auto/jsb_dragonbones_auto.h | 6 +- .../bindings/auto/jsb_editor_support_auto.cpp | 40 +- .../bindings/auto/jsb_editor_support_auto.h | 2 +- .../bindings/auto/jsb_extension_auto.cpp | 2 +- native/cocos/bindings/auto/jsb_gfx_auto.cpp | 3233 +++++++---------- native/cocos/bindings/auto/jsb_gfx_auto.h | 134 +- .../cocos/bindings/auto/jsb_physics_auto.cpp | 14 +- .../cocos/bindings/auto/jsb_pipeline_auto.cpp | 169 +- .../cocos/bindings/auto/jsb_pipeline_auto.h | 8 +- native/cocos/bindings/auto/jsb_scene_auto.cpp | 147 +- native/cocos/bindings/auto/jsb_scene_auto.h | 2 + native/cocos/bindings/auto/jsb_spine_auto.cpp | 244 +- native/cocos/bindings/auto/jsb_spine_auto.h | 6 +- .../cocos/bindings/manual/jsb_conversions.h | 17 +- .../cocos/bindings/manual/jsb_gfx_manual.cpp | 40 - native/cocos/platform/Application.cpp | 2 +- native/cocos/platform/Image.h | 53 +- native/cocos/platform/mac/View.h | 4 +- native/cocos/renderer/GFXDeviceManager.h | 12 +- .../cocos/renderer/frame-graph/Blackboard.h | 2 +- .../cocos/renderer/frame-graph/DevicePass.cpp | 126 +- .../cocos/renderer/frame-graph/DevicePass.h | 7 +- .../frame-graph/DevicePassResourceTable.cpp | 19 +- .../frame-graph/DevicePassResourceTable.h | 11 +- .../cocos/renderer/frame-graph/FrameGraph.cpp | 46 +- .../cocos/renderer/frame-graph/FrameGraph.h | 8 +- .../frame-graph/PassInsertPointManager.cpp | 16 +- .../frame-graph/PassInsertPointManager.h | 16 +- .../cocos/renderer/frame-graph/PassNode.cpp | 88 +- native/cocos/renderer/frame-graph/PassNode.h | 37 +- .../frame-graph/RenderTargetAttachment.h | 1 + native/cocos/renderer/frame-graph/Resource.h | 57 +- .../renderer/frame-graph/ResourceAllocator.h | 6 +- .../renderer/frame-graph/ResourceEntry.h | 14 +- .../cocos/renderer/frame-graph/ResourceNode.h | 2 + .../renderer/frame-graph/VirtualResource.h | 16 +- .../cocos/renderer/gfx-agent/BufferAgent.cpp | 7 +- .../renderer/gfx-agent/CommandBufferAgent.cpp | 2 +- .../renderer/gfx-agent/DescriptorSetAgent.cpp | 5 +- .../gfx-agent/DescriptorSetLayoutAgent.cpp | 2 +- .../cocos/renderer/gfx-agent/DeviceAgent.cpp | 99 +- native/cocos/renderer/gfx-agent/DeviceAgent.h | 32 +- .../renderer/gfx-agent/FramebufferAgent.cpp | 2 +- .../gfx-agent/InputAssemblerAgent.cpp | 30 +- .../renderer/gfx-agent/InputAssemblerAgent.h | 14 +- .../gfx-agent/PipelineLayoutAgent.cpp | 2 +- .../renderer/gfx-agent/PipelineStateAgent.cpp | 2 +- .../cocos/renderer/gfx-agent/QueueAgent.cpp | 2 +- .../renderer/gfx-agent/RenderPassAgent.cpp | 2 +- .../cocos/renderer/gfx-agent/SamplerAgent.cpp | 73 - .../cocos/renderer/gfx-agent/ShaderAgent.cpp | 2 +- .../renderer/gfx-agent/SwapchainAgent.cpp | 127 + .../SwapchainAgent.h} | 15 +- .../cocos/renderer/gfx-agent/TextureAgent.cpp | 24 +- .../cocos/renderer/gfx-agent/TextureAgent.h | 7 +- native/cocos/renderer/gfx-base/GFXBase.h | 8 +- .../renderer/gfx-base/GFXCommandBuffer.h | 25 +- native/cocos/renderer/gfx-base/GFXContext.h | 60 - .../cocos/renderer/gfx-base/GFXDef-common.h | 661 ++-- native/cocos/renderer/gfx-base/GFXDef.cpp | 8 +- native/cocos/renderer/gfx-base/GFXDef.h | 50 +- native/cocos/renderer/gfx-base/GFXDevice.cpp | 48 +- native/cocos/renderer/gfx-base/GFXDevice.h | 135 +- .../renderer/gfx-base/GFXFramebuffer.cpp | 12 +- .../renderer/gfx-base/GFXInputAssembler.cpp | 27 +- .../renderer/gfx-base/GFXInputAssembler.h | 43 +- native/cocos/renderer/gfx-base/GFXObject.h | 1 - .../renderer/gfx-base/GFXPipelineLayout.h | 2 +- native/cocos/renderer/gfx-base/GFXQueue.h | 2 - .../cocos/renderer/gfx-base/GFXRenderPass.cpp | 82 +- native/cocos/renderer/gfx-base/GFXSampler.h | 69 - .../{GFXSampler.cpp => GFXSwapchain.cpp} | 43 +- native/cocos/renderer/gfx-base/GFXSwapchain.h | 96 + native/cocos/renderer/gfx-base/GFXTexture.cpp | 122 +- native/cocos/renderer/gfx-base/GFXTexture.h | 63 +- native/cocos/renderer/gfx-base/SPIRVUtils.cpp | 236 ++ native/cocos/renderer/gfx-base/SPIRVUtils.h | 68 + .../{ => states}/GFXGlobalBarrier.cpp | 7 +- .../gfx-base/{ => states}/GFXGlobalBarrier.h | 15 +- .../states/GFXSampler.cpp} | 33 +- .../states/GFXSampler.h} | 14 +- .../{ => states}/GFXTextureBarrier.cpp | 9 +- .../gfx-base/{ => states}/GFXTextureBarrier.h | 16 +- .../cocos/renderer/gfx-empty/EmptyDevice.cpp | 41 +- native/cocos/renderer/gfx-empty/EmptyDevice.h | 18 +- .../cocos/renderer/gfx-empty/EmptySampler.cpp | 38 - .../EmptySwapchain.cpp} | 41 +- .../EmptySwapchain.h} | 15 +- .../cocos/renderer/gfx-empty/EmptyTexture.cpp | 4 + .../cocos/renderer/gfx-empty/EmptyTexture.h | 2 + .../renderer/gfx-gles2/GLES2CommandBuffer.cpp | 2 +- .../renderer/gfx-gles2/GLES2CommandBuffer.h | 6 +- .../renderer/gfx-gles2/GLES2Commands.cpp | 251 +- .../cocos/renderer/gfx-gles2/GLES2Commands.h | 23 +- .../cocos/renderer/gfx-gles2/GLES2Context.cpp | 581 --- .../cocos/renderer/gfx-gles2/GLES2Context.h | 103 - .../cocos/renderer/gfx-gles2/GLES2Context.mm | 223 -- .../renderer/gfx-gles2/GLES2DescriptorSet.cpp | 2 +- .../renderer/gfx-gles2/GLES2DescriptorSet.h | 8 +- .../gfx-gles2/GLES2DescriptorSetLayout.h | 8 +- .../cocos/renderer/gfx-gles2/GLES2Device.cpp | 155 +- native/cocos/renderer/gfx-gles2/GLES2Device.h | 51 +- .../renderer/gfx-gles2/GLES2Framebuffer.h | 3 +- .../renderer/gfx-gles2/GLES2GPUContext.cpp | 400 ++ .../renderer/gfx-gles2/GLES2GPUObjects.h | 180 +- .../gfx-gles2/GLES2InputAssembler.cpp | 10 - .../renderer/gfx-gles2/GLES2InputAssembler.h | 5 +- .../renderer/gfx-gles2/GLES2PipelineLayout.h | 8 +- .../renderer/gfx-gles2/GLES2PipelineState.h | 3 +- .../gfx-gles2/GLES2PrimaryCommandBuffer.cpp | 1 + .../gfx-gles2/GLES2PrimaryCommandBuffer.h | 1 - native/cocos/renderer/gfx-gles2/GLES2Queue.h | 3 +- .../renderer/gfx-gles2/GLES2RenderPass.cpp | 11 +- .../renderer/gfx-gles2/GLES2RenderPass.h | 3 +- native/cocos/renderer/gfx-gles2/GLES2Shader.h | 3 +- .../renderer/gfx-gles2/GLES2Swapchain.cpp | 155 + .../cocos/renderer/gfx-gles2/GLES2Swapchain.h | 54 + .../cocos/renderer/gfx-gles2/GLES2Texture.cpp | 61 +- .../cocos/renderer/gfx-gles2/GLES2Texture.h | 4 +- .../cocos/renderer/gfx-gles2/GLES2Wrangler.mm | 110 - .../gfx-gles2/{ => states}/GLES2Sampler.cpp | 28 +- .../states/GLES2Sampler.h} | 26 +- .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 3 +- .../renderer/gfx-gles3/GLES3CommandBuffer.h | 7 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 379 +- .../cocos/renderer/gfx-gles3/GLES3Commands.h | 14 +- .../cocos/renderer/gfx-gles3/GLES3Context.cpp | 619 ---- .../cocos/renderer/gfx-gles3/GLES3Context.h | 102 - .../cocos/renderer/gfx-gles3/GLES3Context.mm | 225 -- .../renderer/gfx-gles3/GLES3DescriptorSet.cpp | 2 +- .../renderer/gfx-gles3/GLES3DescriptorSet.h | 8 +- .../gfx-gles3/GLES3DescriptorSetLayout.h | 8 +- .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 159 +- native/cocos/renderer/gfx-gles3/GLES3Device.h | 40 +- .../renderer/gfx-gles3/GLES3Framebuffer.h | 3 +- .../renderer/gfx-gles3/GLES3GPUContext.cpp | 422 +++ .../renderer/gfx-gles3/GLES3GPUObjects.h | 239 +- .../renderer/gfx-gles3/GLES3GlobalBarrier.cpp | 127 - .../gfx-gles3/GLES3InputAssembler.cpp | 10 - .../renderer/gfx-gles3/GLES3InputAssembler.h | 5 +- .../gfx-gles3/GLES3PipelineLayout.cpp | 13 +- .../renderer/gfx-gles3/GLES3PipelineLayout.h | 8 +- .../renderer/gfx-gles3/GLES3PipelineState.h | 3 +- .../gfx-gles3/GLES3PrimaryCommandBuffer.cpp | 3 +- native/cocos/renderer/gfx-gles3/GLES3Queue.h | 3 +- .../renderer/gfx-gles3/GLES3RenderPass.cpp | 18 +- .../renderer/gfx-gles3/GLES3RenderPass.h | 3 +- native/cocos/renderer/gfx-gles3/GLES3Shader.h | 3 +- .../renderer/gfx-gles3/GLES3Swapchain.cpp | 155 + .../cocos/renderer/gfx-gles3/GLES3Swapchain.h | 54 + .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 43 +- .../cocos/renderer/gfx-gles3/GLES3Texture.h | 4 +- .../cocos/renderer/gfx-gles3/GLES3Wrangler.mm | 110 - .../states/GLES3GlobalBarrier.cpp} | 17 +- .../{ => states}/GLES3GlobalBarrier.h | 12 +- .../gfx-gles3/{ => states}/GLES3Sampler.cpp | 28 +- .../gfx-gles3/{ => states}/GLES3Sampler.h | 10 +- native/cocos/renderer/gfx-metal/MTLBuffer.h | 2 +- .../renderer/gfx-metal/MTLCommandBuffer.h | 19 +- .../renderer/gfx-metal/MTLCommandBuffer.mm | 250 +- native/cocos/renderer/gfx-metal/MTLContext.mm | 70 - native/cocos/renderer/gfx-metal/MTLDevice.h | 39 +- native/cocos/renderer/gfx-metal/MTLDevice.mm | 178 +- .../cocos/renderer/gfx-metal/MTLFramebuffer.h | 6 +- .../renderer/gfx-metal/MTLFramebuffer.mm | 29 +- .../cocos/renderer/gfx-metal/MTLGPUObjects.h | 44 +- .../renderer/gfx-metal/MTLPipelineState.h | 4 +- .../renderer/gfx-metal/MTLPipelineState.mm | 33 +- native/cocos/renderer/gfx-metal/MTLQueue.h | 12 +- native/cocos/renderer/gfx-metal/MTLQueue.mm | 56 +- .../cocos/renderer/gfx-metal/MTLRenderPass.mm | 20 +- native/cocos/renderer/gfx-metal/MTLSampler.h | 7 +- native/cocos/renderer/gfx-metal/MTLSampler.mm | 41 +- native/cocos/renderer/gfx-metal/MTLShader.h | 3 + native/cocos/renderer/gfx-metal/MTLShader.mm | 31 +- .../MTLSwapchain.h} | 47 +- .../cocos/renderer/gfx-metal/MTLSwapchain.mm | 174 + native/cocos/renderer/gfx-metal/MTLTexture.h | 19 +- native/cocos/renderer/gfx-metal/MTLTexture.mm | 179 +- native/cocos/renderer/gfx-metal/MTLUtils.h | 2 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 217 +- .../gfx-validator/BufferValidator.cpp | 24 +- .../renderer/gfx-validator/BufferValidator.h | 6 +- .../gfx-validator/CommandBufferValidator.cpp | 6 + .../gfx-validator/CommandBufferValidator.h | 2 +- .../DescriptorSetLayoutValidator.cpp | 2 +- .../gfx-validator/DescriptorSetValidator.cpp | 5 +- .../gfx-validator/DeviceValidator.cpp | 69 +- .../renderer/gfx-validator/DeviceValidator.h | 35 +- .../gfx-validator/FramebufferValidator.cpp | 2 +- .../gfx-validator/InputAssemblerValidator.cpp | 30 +- .../gfx-validator/InputAssemblerValidator.h | 14 +- .../gfx-validator/PipelineLayoutValidator.cpp | 2 +- .../gfx-validator/PipelineStateValidator.cpp | 2 +- .../renderer/gfx-validator/QueueValidator.cpp | 2 +- .../gfx-validator/RenderPassValidator.cpp | 10 +- .../gfx-validator/ShaderValidator.cpp | 2 +- .../gfx-validator/SwapchainValidator.cpp | 94 + .../SwapchainValidator.h} | 15 +- .../gfx-validator/TextureValidator.cpp | 12 +- .../renderer/gfx-validator/TextureValidator.h | 4 + .../gfx-validator/ValidationUtils.cpp | 3 +- .../renderer/gfx-validator/ValidationUtils.h | 2 +- native/cocos/renderer/gfx-vulkan/VKBuffer.cpp | 8 +- .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 105 +- .../renderer/gfx-vulkan/VKCommandBuffer.h | 2 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 378 +- .../cocos/renderer/gfx-vulkan/VKContext.cpp | 566 --- native/cocos/renderer/gfx-vulkan/VKContext.h | 79 - .../renderer/gfx-vulkan/VKDescriptorSet.cpp | 8 +- .../gfx-vulkan/VKDescriptorSetLayout.cpp | 4 +- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 487 +-- native/cocos/renderer/gfx-vulkan/VKDevice.h | 31 +- .../renderer/gfx-vulkan/VKFramebuffer.cpp | 4 +- .../renderer/gfx-vulkan/VKGPUContext.cpp | 333 ++ .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 247 +- .../renderer/gfx-vulkan/VKInputAssembler.cpp | 15 +- .../renderer/gfx-vulkan/VKPipelineLayout.cpp | 8 +- .../renderer/gfx-vulkan/VKPipelineState.cpp | 4 +- native/cocos/renderer/gfx-vulkan/VKQueue.cpp | 34 +- .../renderer/gfx-vulkan/VKRenderPass.cpp | 15 +- native/cocos/renderer/gfx-vulkan/VKSPIRV.h | 120 - native/cocos/renderer/gfx-vulkan/VKShader.cpp | 12 +- .../cocos/renderer/gfx-vulkan/VKSwapchain.cpp | 430 +++ .../cocos/renderer/gfx-vulkan/VKSwapchain.h | 66 + .../cocos/renderer/gfx-vulkan/VKTexture.cpp | 69 +- native/cocos/renderer/gfx-vulkan/VKTexture.h | 6 +- native/cocos/renderer/gfx-vulkan/VKUtils.cpp | 52 +- native/cocos/renderer/gfx-vulkan/VKUtils.h | 6 +- .../{ => states}/VKGlobalBarrier.cpp | 20 +- .../gfx-vulkan/{ => states}/VKGlobalBarrier.h | 16 +- .../gfx-vulkan/{ => states}/VKSampler.cpp | 36 +- .../gfx-vulkan/{ => states}/VKSampler.h | 10 +- .../{ => states}/VKTextureBarrier.cpp | 34 +- .../{ => states}/VKTextureBarrier.h | 16 +- .../cocos/renderer/pipeline/BatchedBuffer.cpp | 2 +- native/cocos/renderer/pipeline/Define.cpp | 131 +- native/cocos/renderer/pipeline/Define.h | 74 +- .../pipeline/GlobalDescriptorSetManager.cpp | 31 +- .../renderer/pipeline/InstancedBuffer.cpp | 2 +- .../cocos/renderer/pipeline/PipelineUBO.cpp | 22 +- native/cocos/renderer/pipeline/PipelineUBO.h | 4 +- .../pipeline/RenderAdditiveLightQueue.cpp | 26 +- .../renderer/pipeline/RenderPipeline.cpp | 5 +- .../cocos/renderer/pipeline/RenderPipeline.h | 19 +- .../cocos/renderer/pipeline/SceneCulling.cpp | 9 +- .../pipeline/deferred/DeferredPipeline.cpp | 218 +- .../pipeline/deferred/DeferredPipeline.h | 63 +- .../pipeline/deferred/GbufferStage.cpp | 94 +- .../pipeline/deferred/LightingStage.cpp | 408 +-- .../pipeline/deferred/LightingStage.h | 37 +- .../renderer/pipeline/deferred/MainFlow.cpp | 2 - .../pipeline/deferred/PostprocessStage.cpp | 205 +- .../pipeline/deferred/PostprocessStage.h | 6 - .../pipeline/deferred/ReflectionComp.cpp | 24 +- .../pipeline/forward/ForwardPipeline.cpp | 50 +- .../pipeline/forward/ForwardPipeline.h | 4 +- .../pipeline/forward/ForwardStage.cpp | 25 +- .../renderer/pipeline/forward/UIPhase.cpp | 37 +- .../renderer/pipeline/shadow/ShadowFlow.cpp | 20 +- native/cocos/scene/RenderWindow.h | 15 +- native/cocos/scene/SubModel.h | 15 +- native/docs/LINTER_AUTOFIX_GUIDE.md | 6 +- native/tools/bindings-generator/generator.py | 4 +- .../templates/ifunction_overloaded.c | 2 +- native/tools/gfx-define-generator/generate.js | 78 +- native/tools/license-upgrader/generate.js | 6 +- native/tools/tojs/gfx.ini | 55 +- 281 files changed, 9731 insertions(+), 10953 deletions(-) delete mode 100644 native/cocos/renderer/gfx-agent/SamplerAgent.cpp create mode 100644 native/cocos/renderer/gfx-agent/SwapchainAgent.cpp rename native/cocos/renderer/{gfx-validator/SamplerValidator.h => gfx-agent/SwapchainAgent.h} (75%) delete mode 100644 native/cocos/renderer/gfx-base/GFXContext.h delete mode 100644 native/cocos/renderer/gfx-base/GFXSampler.h rename native/cocos/renderer/gfx-base/{GFXSampler.cpp => GFXSwapchain.cpp} (65%) create mode 100644 native/cocos/renderer/gfx-base/GFXSwapchain.h create mode 100644 native/cocos/renderer/gfx-base/SPIRVUtils.cpp create mode 100644 native/cocos/renderer/gfx-base/SPIRVUtils.h rename native/cocos/renderer/gfx-base/{ => states}/GFXGlobalBarrier.cpp (93%) rename native/cocos/renderer/gfx-base/{ => states}/GFXGlobalBarrier.h (83%) rename native/cocos/renderer/{gfx-metal/MTLContext.h => gfx-base/states/GFXSampler.cpp} (71%) rename native/cocos/renderer/{gfx-empty/EmptyContext.h => gfx-base/states/GFXSampler.h} (83%) rename native/cocos/renderer/gfx-base/{ => states}/GFXTextureBarrier.cpp (93%) rename native/cocos/renderer/gfx-base/{ => states}/GFXTextureBarrier.h (82%) delete mode 100644 native/cocos/renderer/gfx-empty/EmptySampler.cpp rename native/cocos/renderer/{gfx-validator/SamplerValidator.cpp => gfx-empty/EmptySwapchain.cpp} (61%) rename native/cocos/renderer/{gfx-agent/SamplerAgent.h => gfx-empty/EmptySwapchain.h} (79%) delete mode 100644 native/cocos/renderer/gfx-gles2/GLES2Context.cpp delete mode 100644 native/cocos/renderer/gfx-gles2/GLES2Context.h delete mode 100644 native/cocos/renderer/gfx-gles2/GLES2Context.mm create mode 100644 native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp create mode 100644 native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp create mode 100644 native/cocos/renderer/gfx-gles2/GLES2Swapchain.h delete mode 100644 native/cocos/renderer/gfx-gles2/GLES2Wrangler.mm rename native/cocos/renderer/gfx-gles2/{ => states}/GLES2Sampler.cpp (80%) rename native/cocos/renderer/{gfx-base/GFXContext.cpp => gfx-gles2/states/GLES2Sampler.h} (77%) delete mode 100644 native/cocos/renderer/gfx-gles3/GLES3Context.cpp delete mode 100644 native/cocos/renderer/gfx-gles3/GLES3Context.h delete mode 100644 native/cocos/renderer/gfx-gles3/GLES3Context.mm create mode 100644 native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp delete mode 100644 native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.cpp create mode 100644 native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp create mode 100644 native/cocos/renderer/gfx-gles3/GLES3Swapchain.h delete mode 100644 native/cocos/renderer/gfx-gles3/GLES3Wrangler.mm rename native/cocos/renderer/{gfx-empty/EmptyContext.cpp => gfx-gles3/states/GLES3GlobalBarrier.cpp} (77%) rename native/cocos/renderer/gfx-gles3/{ => states}/GLES3GlobalBarrier.h (87%) rename native/cocos/renderer/gfx-gles3/{ => states}/GLES3Sampler.cpp (80%) rename native/cocos/renderer/gfx-gles3/{ => states}/GLES3Sampler.h (91%) delete mode 100644 native/cocos/renderer/gfx-metal/MTLContext.mm rename native/cocos/renderer/{gfx-gles2/GLES2Sampler.h => gfx-metal/MTLSwapchain.h} (63%) create mode 100644 native/cocos/renderer/gfx-metal/MTLSwapchain.mm create mode 100644 native/cocos/renderer/gfx-validator/SwapchainValidator.cpp rename native/cocos/renderer/{gfx-empty/EmptySampler.h => gfx-validator/SwapchainValidator.h} (74%) delete mode 100644 native/cocos/renderer/gfx-vulkan/VKContext.cpp delete mode 100644 native/cocos/renderer/gfx-vulkan/VKContext.h create mode 100644 native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp delete mode 100644 native/cocos/renderer/gfx-vulkan/VKSPIRV.h create mode 100644 native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp create mode 100644 native/cocos/renderer/gfx-vulkan/VKSwapchain.h rename native/cocos/renderer/gfx-vulkan/{ => states}/VKGlobalBarrier.cpp (87%) rename native/cocos/renderer/gfx-vulkan/{ => states}/VKGlobalBarrier.h (83%) rename native/cocos/renderer/gfx-vulkan/{ => states}/VKSampler.cpp (71%) rename native/cocos/renderer/gfx-vulkan/{ => states}/VKSampler.h (91%) rename native/cocos/renderer/gfx-vulkan/{ => states}/VKTextureBarrier.cpp (73%) rename native/cocos/renderer/gfx-vulkan/{ => states}/VKTextureBarrier.h (83%) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 05146c45b5..97ee0f2739 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -384,7 +384,7 @@ elseif(USE_JOB_SYSTEM_TBB) cocos/base/job-system/job-system-tbb/TBBJobSystem.h cocos/base/job-system/job-system-tbb/TBBJobSystem.cpp ) -else() +else() cocos_source_files( cocos/base/job-system/job-system-dummy/DummyJobGraph.h cocos/base/job-system/job-system-dummy/DummyJobGraph.cpp @@ -576,7 +576,7 @@ elseif(ANDROID) ${CWD}/cocos/platform/java/jni/JniImp.cpp ${CWD}/cocos/platform/java/jni/JniImp.h ) - + cocos_source_files(MODULE ccfilesystem cocos/platform/android/FileUtils-android.cpp cocos/platform/android/FileUtils-android.h @@ -616,7 +616,7 @@ elseif(APPLE) cocos/platform/ios/Reachability.h cocos/platform/ios/Reachability.cpp ) - + cocos_source_files(MODULE ccfilesystem cocos/platform/apple/FileUtils-apple.h cocos/platform/apple/FileUtils-apple.mm @@ -644,6 +644,8 @@ endif() cocos_source_files( cocos/renderer/GFXDeviceManager.h + cocos/renderer/gfx-base/SPIRVUtils.h + cocos/renderer/gfx-base/SPIRVUtils.cpp cocos/renderer/gfx-base/GFXObject.h cocos/renderer/gfx-base/GFXObject.cpp cocos/renderer/gfx-base/GFXBase.h @@ -651,8 +653,6 @@ cocos_source_files( cocos/renderer/gfx-base/GFXBuffer.h cocos/renderer/gfx-base/GFXCommandBuffer.cpp cocos/renderer/gfx-base/GFXCommandBuffer.h - cocos/renderer/gfx-base/GFXContext.cpp - cocos/renderer/gfx-base/GFXContext.h cocos/renderer/gfx-base/GFXDef.cpp cocos/renderer/gfx-base/GFXDef.h cocos/renderer/gfx-base/GFXDef-common.h @@ -660,8 +660,6 @@ cocos_source_files( cocos/renderer/gfx-base/GFXDevice.h cocos/renderer/gfx-base/GFXFramebuffer.cpp cocos/renderer/gfx-base/GFXFramebuffer.h - cocos/renderer/gfx-base/GFXGlobalBarrier.cpp - cocos/renderer/gfx-base/GFXGlobalBarrier.h cocos/renderer/gfx-base/GFXInputAssembler.cpp cocos/renderer/gfx-base/GFXInputAssembler.h cocos/renderer/gfx-base/GFXDescriptorSet.cpp @@ -676,14 +674,18 @@ cocos_source_files( cocos/renderer/gfx-base/GFXQueue.h cocos/renderer/gfx-base/GFXRenderPass.cpp cocos/renderer/gfx-base/GFXRenderPass.h - cocos/renderer/gfx-base/GFXSampler.cpp - cocos/renderer/gfx-base/GFXSampler.h cocos/renderer/gfx-base/GFXShader.cpp cocos/renderer/gfx-base/GFXShader.h + cocos/renderer/gfx-base/GFXSwapchain.cpp + cocos/renderer/gfx-base/GFXSwapchain.h cocos/renderer/gfx-base/GFXTexture.cpp cocos/renderer/gfx-base/GFXTexture.h - cocos/renderer/gfx-base/GFXTextureBarrier.cpp - cocos/renderer/gfx-base/GFXTextureBarrier.h + cocos/renderer/gfx-base/states/GFXGlobalBarrier.cpp + cocos/renderer/gfx-base/states/GFXGlobalBarrier.h + cocos/renderer/gfx-base/states/GFXSampler.cpp + cocos/renderer/gfx-base/states/GFXSampler.h + cocos/renderer/gfx-base/states/GFXTextureBarrier.cpp + cocos/renderer/gfx-base/states/GFXTextureBarrier.h cocos/renderer/gfx-agent/BufferAgent.h cocos/renderer/gfx-agent/BufferAgent.cpp @@ -707,8 +709,8 @@ cocos_source_files( cocos/renderer/gfx-agent/QueueAgent.cpp cocos/renderer/gfx-agent/RenderPassAgent.h cocos/renderer/gfx-agent/RenderPassAgent.cpp - cocos/renderer/gfx-agent/SamplerAgent.h - cocos/renderer/gfx-agent/SamplerAgent.cpp + cocos/renderer/gfx-agent/SwapchainAgent.h + cocos/renderer/gfx-agent/SwapchainAgent.cpp cocos/renderer/gfx-agent/ShaderAgent.h cocos/renderer/gfx-agent/ShaderAgent.cpp cocos/renderer/gfx-agent/TextureAgent.h @@ -736,10 +738,10 @@ cocos_source_files( cocos/renderer/gfx-validator/QueueValidator.cpp cocos/renderer/gfx-validator/RenderPassValidator.h cocos/renderer/gfx-validator/RenderPassValidator.cpp - cocos/renderer/gfx-validator/SamplerValidator.h - cocos/renderer/gfx-validator/SamplerValidator.cpp cocos/renderer/gfx-validator/ShaderValidator.h cocos/renderer/gfx-validator/ShaderValidator.cpp + cocos/renderer/gfx-validator/SwapchainValidator.h + cocos/renderer/gfx-validator/SwapchainValidator.cpp cocos/renderer/gfx-validator/TextureValidator.h cocos/renderer/gfx-validator/TextureValidator.cpp cocos/renderer/gfx-validator/ValidationUtils.h @@ -749,8 +751,6 @@ cocos_source_files( cocos/renderer/gfx-empty/EmptyBuffer.cpp cocos/renderer/gfx-empty/EmptyCommandBuffer.h cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp - cocos/renderer/gfx-empty/EmptyContext.h - cocos/renderer/gfx-empty/EmptyContext.cpp cocos/renderer/gfx-empty/EmptyDescriptorSet.h cocos/renderer/gfx-empty/EmptyDescriptorSet.cpp cocos/renderer/gfx-empty/EmptyDescriptorSetLayout.h @@ -769,10 +769,10 @@ cocos_source_files( cocos/renderer/gfx-empty/EmptyQueue.cpp cocos/renderer/gfx-empty/EmptyRenderPass.h cocos/renderer/gfx-empty/EmptyRenderPass.cpp - cocos/renderer/gfx-empty/EmptySampler.h - cocos/renderer/gfx-empty/EmptySampler.cpp cocos/renderer/gfx-empty/EmptyShader.h cocos/renderer/gfx-empty/EmptyShader.cpp + cocos/renderer/gfx-empty/EmptySwapchain.h + cocos/renderer/gfx-empty/EmptySwapchain.cpp cocos/renderer/gfx-empty/EmptyTexture.h cocos/renderer/gfx-empty/EmptyTexture.cpp @@ -902,12 +902,11 @@ if(CC_USE_GLES2) cocos/renderer/gfx-gles2/GLES2CommandBuffer.h cocos/renderer/gfx-gles2/GLES2Commands.cpp cocos/renderer/gfx-gles2/GLES2Commands.h - cocos/renderer/gfx-gles2/GLES2Context.h - cocos/renderer/gfx-gles2/GLES2Context.cpp cocos/renderer/gfx-gles2/GLES2Device.cpp cocos/renderer/gfx-gles2/GLES2Device.h cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp cocos/renderer/gfx-gles2/GLES2Framebuffer.h + cocos/renderer/gfx-gles2/GLES2GPUContext.cpp cocos/renderer/gfx-gles2/GLES2GPUObjects.h cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp cocos/renderer/gfx-gles2/GLES2InputAssembler.h @@ -925,31 +924,19 @@ if(CC_USE_GLES2) cocos/renderer/gfx-gles2/GLES2Queue.h cocos/renderer/gfx-gles2/GLES2RenderPass.cpp cocos/renderer/gfx-gles2/GLES2RenderPass.h - cocos/renderer/gfx-gles2/GLES2Sampler.cpp - cocos/renderer/gfx-gles2/GLES2Sampler.h cocos/renderer/gfx-gles2/GLES2Shader.cpp cocos/renderer/gfx-gles2/GLES2Shader.h + cocos/renderer/gfx-gles2/GLES2Swapchain.cpp + cocos/renderer/gfx-gles2/GLES2Swapchain.h cocos/renderer/gfx-gles2/GLES2Std.cpp cocos/renderer/gfx-gles2/GLES2Std.h cocos/renderer/gfx-gles2/GLES2Texture.cpp cocos/renderer/gfx-gles2/GLES2Texture.h + cocos/renderer/gfx-gles2/GLES2Wrangler.cpp cocos/renderer/gfx-gles2/GLES2Wrangler.h + cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp + cocos/renderer/gfx-gles2/states/GLES2Sampler.h ) - - if(APPLE) - cocos_source_files( - NO_WERROR cocos/renderer/gfx-gles2/GLES2Wrangler.mm - ) - else() - cocos_source_files( - cocos/renderer/gfx-gles2/GLES2Wrangler.cpp - ) - endif() - if(IOS) - cocos_source_files( - NO_WERROR cocos/renderer/gfx-gles2/GLES2Context.mm - ) - endif() endif() if(CC_USE_GLES3) @@ -961,14 +948,11 @@ if(CC_USE_GLES3) cocos/renderer/gfx-gles3/GLES3CommandBuffer.h cocos/renderer/gfx-gles3/GLES3Commands.cpp cocos/renderer/gfx-gles3/GLES3Commands.h - cocos/renderer/gfx-gles3/GLES3Context.cpp - cocos/renderer/gfx-gles3/GLES3Context.h cocos/renderer/gfx-gles3/GLES3Device.cpp cocos/renderer/gfx-gles3/GLES3Device.h cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp cocos/renderer/gfx-gles3/GLES3Framebuffer.h - cocos/renderer/gfx-gles3/GLES3GlobalBarrier.cpp - cocos/renderer/gfx-gles3/GLES3GlobalBarrier.h + cocos/renderer/gfx-gles3/GLES3GPUContext.cpp cocos/renderer/gfx-gles3/GLES3GPUObjects.h cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp cocos/renderer/gfx-gles3/GLES3InputAssembler.h @@ -986,30 +970,21 @@ if(CC_USE_GLES3) cocos/renderer/gfx-gles3/GLES3Queue.h cocos/renderer/gfx-gles3/GLES3RenderPass.cpp cocos/renderer/gfx-gles3/GLES3RenderPass.h - cocos/renderer/gfx-gles3/GLES3Sampler.cpp - cocos/renderer/gfx-gles3/GLES3Sampler.h cocos/renderer/gfx-gles3/GLES3Shader.cpp cocos/renderer/gfx-gles3/GLES3Shader.h + cocos/renderer/gfx-gles3/GLES3Swapchain.cpp + cocos/renderer/gfx-gles3/GLES3Swapchain.h cocos/renderer/gfx-gles3/GLES3Std.cpp cocos/renderer/gfx-gles3/GLES3Std.h cocos/renderer/gfx-gles3/GLES3Texture.cpp cocos/renderer/gfx-gles3/GLES3Texture.h + cocos/renderer/gfx-gles3/GLES3Wrangler.cpp cocos/renderer/gfx-gles3/GLES3Wrangler.h + cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.cpp + cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.h + cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp + cocos/renderer/gfx-gles3/states/GLES3Sampler.h ) - if(APPLE) - cocos_source_files( - NO_WERROR cocos/renderer/gfx-gles3/GLES3Wrangler.mm - ) - else() - cocos_source_files( - cocos/renderer/gfx-gles3/GLES3Wrangler.cpp - ) - endif() - if(IOS) - cocos_source_files( - NO_WERROR cocos/renderer/gfx-gles3/GLES3Context.mm - ) - endif() endif() if(CC_USE_METAL) @@ -1019,8 +994,6 @@ if(CC_USE_METAL) cocos/renderer/gfx-metal/MTLBuffer.mm cocos/renderer/gfx-metal/MTLCommandBuffer.h cocos/renderer/gfx-metal/MTLCommandBuffer.mm - cocos/renderer/gfx-metal/MTLContext.h - NO_WERROR cocos/renderer/gfx-metal/MTLContext.mm # CAMetalLayer bug for apple cocos/renderer/gfx-metal/MTLDevice.h NO_WERROR cocos/renderer/gfx-metal/MTLDevice.mm # CAMetalLayer bug for apple cocos/renderer/gfx-metal/MTLFramebuffer.mm @@ -1055,6 +1028,8 @@ if(CC_USE_METAL) cocos/renderer/gfx-metal/MTLCommandEncoder.h cocos/renderer/gfx-metal/MTLConfig.h cocos/renderer/gfx-metal/MTLSemaphore.h + cocos/renderer/gfx-metal/MTLSwapchain.h + cocos/renderer/gfx-metal/MTLSwapchain.mm ) endif() @@ -1069,14 +1044,11 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/VKCommandBuffer.h cocos/renderer/gfx-vulkan/VKCommands.cpp cocos/renderer/gfx-vulkan/VKCommands.h - cocos/renderer/gfx-vulkan/VKContext.cpp - cocos/renderer/gfx-vulkan/VKContext.h cocos/renderer/gfx-vulkan/VKDevice.cpp cocos/renderer/gfx-vulkan/VKDevice.h cocos/renderer/gfx-vulkan/VKFramebuffer.cpp cocos/renderer/gfx-vulkan/VKFramebuffer.h - cocos/renderer/gfx-vulkan/VKGlobalBarrier.cpp - cocos/renderer/gfx-vulkan/VKGlobalBarrier.h + cocos/renderer/gfx-vulkan/VKGPUContext.cpp cocos/renderer/gfx-vulkan/VKGPUObjects.h cocos/renderer/gfx-vulkan/VKInputAssembler.cpp cocos/renderer/gfx-vulkan/VKInputAssembler.h @@ -1092,21 +1064,24 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/VKQueue.h cocos/renderer/gfx-vulkan/VKRenderPass.cpp cocos/renderer/gfx-vulkan/VKRenderPass.h - cocos/renderer/gfx-vulkan/VKSampler.cpp - cocos/renderer/gfx-vulkan/VKSampler.h cocos/renderer/gfx-vulkan/VKShader.cpp cocos/renderer/gfx-vulkan/VKShader.h - cocos/renderer/gfx-vulkan/VKSPIRV.h cocos/renderer/gfx-vulkan/VKStd.cpp cocos/renderer/gfx-vulkan/VKStd.h + cocos/renderer/gfx-vulkan/VKSwapchain.cpp + cocos/renderer/gfx-vulkan/VKSwapchain.h cocos/renderer/gfx-vulkan/VKTexture.cpp cocos/renderer/gfx-vulkan/VKTexture.h - cocos/renderer/gfx-vulkan/VKTextureBarrier.cpp - cocos/renderer/gfx-vulkan/VKTextureBarrier.h cocos/renderer/gfx-vulkan/VKUtils.cpp cocos/renderer/gfx-vulkan/VKUtils.h cocos/renderer/gfx-vulkan/volk.c cocos/renderer/gfx-vulkan/volk.h + cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.cpp + cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.h + cocos/renderer/gfx-vulkan/states/VKSampler.cpp + cocos/renderer/gfx-vulkan/states/VKSampler.h + cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp + cocos/renderer/gfx-vulkan/states/VKTextureBarrier.h ) if(ANDROID) @@ -1611,7 +1586,7 @@ elseif(WIN32) ) endif() -############# module bindings +############# module bindings if(USE_SE_V8) cocos_source_files(MODULE ccbindings cocos/bindings/jswrapper/v8/Base.h @@ -1695,7 +1670,7 @@ cocos_source_files(MODULE ccbindings cocos/bindings/jswrapper/State.cpp cocos/bindings/jswrapper/State.h cocos/bindings/jswrapper/Value.cpp - cocos/bindings/jswrapper/Value.h + cocos/bindings/jswrapper/Value.h NO_WERROR cocos/bindings/manual/jsb_global_init.cpp cocos/bindings/manual/jsb_global_init.h ) @@ -1860,12 +1835,12 @@ if(USE_MODULES) target_link_libraries(ccunzip PUBLIC ${ZLIB} ) - target_link_libraries(ccfilesystem PUBLIC - ccunzip + target_link_libraries(ccfilesystem PUBLIC + ccunzip ccutils cclog ) - target_link_libraries(ccbindings PUBLIC + target_link_libraries(ccbindings PUBLIC ccfilesystem cclog ${se_libs_name} @@ -2020,7 +1995,7 @@ target_compile_definitions(cocos2d ${CC_EXTERNAL_PRIVATE_DEFINITIONS} ) if(NOT OHOS) - target_include_directories(cocos2d PUBLIC + target_include_directories(cocos2d PUBLIC ${CWD}/external/sources/EGL ${CWD}/external/sources/khronos ) @@ -2127,6 +2102,7 @@ if(APPLE) "-framework UIKit" "-framework AVKit" "-framework WebKit" + "-framework CoreVideo" "-framework CoreMotion" "-framework CFNetwork" "-framework CoreMedia" diff --git a/native/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index 935f201b41..6dc7871c80 100644 --- a/native/cocos/base/IndexHandle.h +++ b/native/cocos/base/IndexHandle.h @@ -49,7 +49,7 @@ public: inline bool operator<(IndexHandle const &rhs) const noexcept; inline bool operator==(IndexHandle const &rhs) const noexcept; inline bool operator!=(IndexHandle const &rhs) const noexcept; - inline operator IndexType() const noexcept; + inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicity static IndexType constexpr UNINITIALIZED{std::numeric_limits::max()}; diff --git a/native/cocos/base/Macros.h b/native/cocos/base/Macros.h index 9777158104..930ff469d5 100644 --- a/native/cocos/base/Macros.h +++ b/native/cocos/base/Macros.h @@ -408,13 +408,13 @@ It should work same as apples CFSwapInt32LittleToHost(..) cls(const cls &) = delete; \ cls &operator=(const cls &) = delete; -#define ENABLE_MOVE_SEMANTICS(cls) \ - cls(cls &&) = default; \ - cls &operator=(cls &&) = default; +#define ENABLE_MOVE_SEMANTICS(cls) \ + cls(cls &&) noexcept = default; \ + cls &operator=(cls &&) noexcept = default; #define DISABLE_MOVE_SEMANTICS(cls) \ - cls(cls &&) = delete; \ - cls &operator=(cls &&) = delete; + cls(cls &&) noexcept = delete; \ + cls &operator=(cls &&) noexcept = delete; #if (CC_COMPILER == CC_COMPILER_MSVC) #define CC_ALIGN(N) __declspec(align(N)) @@ -604,9 +604,9 @@ It should work same as apples CFSwapInt32LittleToHost(..) #define ENABLE_IF_T3_RET(t1, t2, t3) std::enable_if_t::value || std::is_same::value || std::is_same::value, void> #if defined(__GNUC__) && __GNUC__ >= 4 - #define CC_PREDICT_TRUE(x) __builtin_expect(!!(x), 1) + #define CC_PREDICT_TRUE(x) __builtin_expect(!!(x), 1) #define CC_PREDICT_FALSE(x) __builtin_expect(!!(x), 0) #else - #define CC_PREDICT_TRUE(x) (x) + #define CC_PREDICT_TRUE(x) (x) #define CC_PREDICT_FALSE(x) (x) #endif \ No newline at end of file diff --git a/native/cocos/base/Map.h b/native/cocos/base/Map.h index dc0fd677c5..492336c441 100644 --- a/native/cocos/base/Map.h +++ b/native/cocos/base/Map.h @@ -86,21 +86,18 @@ public: Map() : _data() { static_assert(std::is_convertible::value, "Invalid Type for cc::Map!"); - CC_LOG_INFO("In the default constructor of Map!"); } /** Constructor with capacity. */ explicit Map(ssize_t capacity) : _data() { static_assert(std::is_convertible::value, "Invalid Type for cc::Map!"); - CC_LOG_INFO("In the constructor with capacity of Map!"); _data.reserve(capacity); } /** Copy constructor. */ Map(const Map &other) { static_assert(std::is_convertible::value, "Invalid Type for cc::Map!"); - CC_LOG_INFO("In the copy constructor of Map!"); _data = other._data; addRefForAllObjects(); } @@ -108,7 +105,6 @@ public: /** Move constructor. */ Map(Map &&other) noexcept { static_assert(std::is_convertible::value, "Invalid Type for cc::Map!"); - CC_LOG_INFO("In the move constructor of Map!"); _data = std::move(other._data); } @@ -117,7 +113,6 @@ public: * It will release all objects in map. */ ~Map() { - CC_LOG_INFO("In the destructor of Map!"); clear(); } @@ -317,7 +312,6 @@ public: /** Copy assignment operator. */ Map &operator=(const Map &other) { if (this != &other) { - CC_LOG_INFO("In the copy assignment operator of Map!"); clear(); _data = other._data; addRefForAllObjects(); @@ -328,7 +322,6 @@ public: /** Move assignment operator. */ Map &operator=(Map &&other) noexcept { if (this != &other) { - CC_LOG_INFO("In the move assignment operator of Map!"); clear(); _data = std::move(other._data); } diff --git a/native/cocos/base/StringPool.h b/native/cocos/base/StringPool.h index dc921b9d2a..8f47c74674 100644 --- a/native/cocos/base/StringPool.h +++ b/native/cocos/base/StringPool.h @@ -25,11 +25,11 @@ #pragma once -#include #include #include #include #include "StringHandle.h" +#include "base/Macros.h" #include "threading/ReadWriteLock.h" namespace cc { @@ -120,8 +120,8 @@ inline StringHandle StringPool::doStringToHandle(const char *str) no } template -inline char const *StringPool::doHandleToString(const StringHandle &handle) const noexcept { - assert(handle < _handleToStrings.size()); +inline const char *StringPool::doHandleToString(const StringHandle &handle) const noexcept { + CC_ASSERT(handle < _handleToStrings.size()); return _handleToStrings[handle]; } diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index e937e1fe30..5962e838db 100755 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -60,6 +60,12 @@ using FlagBits = uint32_t; using ValueType = std::underlying_type::type; \ return (static_cast(flags) & static_cast(flagsToTest)) == static_cast(flagsToTest); \ } \ - inline T addFlags(const T flags, const T flagsToAdd) { return (flags | flagsToAdd); } \ - inline T removeFlags(const T flags, const T flagsToRemove) { return (flags & ~flagsToRemove); } \ + inline T addFlags(T &flags, const T flagsToAdd) { \ + flags |= flagsToAdd; \ + return flags; \ + } \ + inline T removeFlags(T &flags, const T flagsToRemove) { \ + flags &= ~flagsToRemove; \ + return flags; \ + } \ CC_ENUM_CONVERSION_OPERATOR(T) diff --git a/native/cocos/base/Utils.h b/native/cocos/base/Utils.h index f1b500145d..22d2b92479 100644 --- a/native/cocos/base/Utils.h +++ b/native/cocos/base/Utils.h @@ -64,11 +64,6 @@ CC_DLL double atof(const char *str); CC_DLL uint alignTo(uint size, uint alignment); -template -char (*countOfHelper(T (&array)[Size]))[Size]; - -#define COUNTOF(array) (sizeof(*countOfHelper(array)) + 0) - template uint toUint(T value) { static_assert(std::is_arithmetic::value, "T must be numeric"); diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp index 631650e9dc..b463528ce3 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp @@ -25,12 +25,14 @@ #include "ThreadSafeLinearAllocator.h" #include "acl/core/memory_utils.h" +#include "base/Macros.h" namespace cc { ThreadSafeLinearAllocator::ThreadSafeLinearAllocator(uint32_t size) noexcept : _capacity(size) { _buffer = malloc(size); + CCASSERT(_buffer, "Out of memory"); } ThreadSafeLinearAllocator::~ThreadSafeLinearAllocator() { diff --git a/native/cocos/bindings/auto/jsb_audio_auto.cpp b/native/cocos/bindings/auto/jsb_audio_auto.cpp index 813aee8937..1788b4d570 100644 --- a/native/cocos/bindings/auto/jsb_audio_auto.cpp +++ b/native/cocos/bindings/auto/jsb_audio_auto.cpp @@ -158,108 +158,6 @@ static bool js_audio_AudioEngine_lazyInit(se::State& s) // NOLINT(readability-id } SE_BIND_FUNC(js_audio_AudioEngine_lazyInit) -static bool js_audio_AudioEngine_setCurrentTime(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setCurrentTime : Error processing arguments"); - bool result = cc::AudioEngine::setCurrentTime(arg0.value(), arg1.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setCurrentTime : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_setCurrentTime) - -static bool js_audio_AudioEngine_getVolume(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getVolume : Error processing arguments"); - float result = cc::AudioEngine::getVolume(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getVolume : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_getVolume) - -static bool js_audio_AudioEngine_uncache(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_uncache : Error processing arguments"); - cc::AudioEngine::uncache(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_uncache) - -static bool js_audio_AudioEngine_resumeAll(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::AudioEngine::resumeAll(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_resumeAll) - -static bool js_audio_AudioEngine_stopAll(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::AudioEngine::stopAll(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_stopAll) - -static bool js_audio_AudioEngine_pause(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_pause : Error processing arguments"); - cc::AudioEngine::pause(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_pause) - static bool js_audio_AudioEngine_end(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -273,241 +171,22 @@ static bool js_audio_AudioEngine_end(se::State& s) // NOLINT(readability-identif } SE_BIND_FUNC(js_audio_AudioEngine_end) -static bool js_audio_AudioEngine_getMaxAudioInstance(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_audio_AudioEngine_getDefaultProfile(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - int result = cc::AudioEngine::getMaxAudioInstance(); + cc::AudioProfile* result = cc::AudioEngine::getDefaultProfile(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getMaxAudioInstance : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDefaultProfile : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_audio_AudioEngine_getMaxAudioInstance) - -static bool js_audio_AudioEngine_isEnabled(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - bool result = cc::AudioEngine::isEnabled(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isEnabled : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_isEnabled) - -static bool js_audio_AudioEngine_getDurationFromFile(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDurationFromFile : Error processing arguments"); - float result = cc::AudioEngine::getDurationFromFile(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDurationFromFile : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_getDurationFromFile) - -static bool js_audio_AudioEngine_getCurrentTime(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getCurrentTime : Error processing arguments"); - float result = cc::AudioEngine::getCurrentTime(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getCurrentTime : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_getCurrentTime) - -static bool js_audio_AudioEngine_setMaxAudioInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setMaxAudioInstance : Error processing arguments"); - bool result = cc::AudioEngine::setMaxAudioInstance(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setMaxAudioInstance : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_setMaxAudioInstance) - -static bool js_audio_AudioEngine_isLoop(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isLoop : Error processing arguments"); - bool result = cc::AudioEngine::isLoop(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isLoop : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_isLoop) - -static bool js_audio_AudioEngine_pauseAll(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::AudioEngine::pauseAll(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_pauseAll) - -static bool js_audio_AudioEngine_uncacheAll(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::AudioEngine::uncacheAll(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_uncacheAll) - -static bool js_audio_AudioEngine_setVolume(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setVolume : Error processing arguments"); - cc::AudioEngine::setVolume(arg0.value(), arg1.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_setVolume) - -static bool js_audio_AudioEngine_preload(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - do { - if (argc == 2) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - HolderType, true> arg1 = {}; - do { - if (args[1].isObject() && args[1].toObject()->isFunction()) - { - se::Value jsThis(s.thisObject()); - se::Value jsFunc(args[1]); - jsFunc.toObject()->root(); - auto lambda = [=](bool larg0) -> void { - se::ScriptEngine::getInstance()->clearException(); - se::AutoHandleScope hs; - - CC_UNUSED bool ok = true; - se::ValueArray args; - args.resize(1); - ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); - se::Value rval; - se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; - se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); - if (!succeed) { - se::ScriptEngine::getInstance()->clearException(); - } - }; - arg1.data = lambda; - } - else - { - arg1.data = nullptr; - } - } while(false) - ; - if (!ok) { ok = true; break; } - cc::AudioEngine::preload(arg0.value(), arg1.value()); - return true; - } - } while (false); - do { - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - cc::AudioEngine::preload(arg0.value()); - return true; - } - } while (false); - SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_preload) - -static bool js_audio_AudioEngine_setEnabled(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setEnabled : Error processing arguments"); - cc::AudioEngine::setEnabled(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_setEnabled) +SE_BIND_FUNC(js_audio_AudioEngine_getDefaultProfile) static bool js_audio_AudioEngine_play2d(se::State& s) // NOLINT(readability-identifier-naming) { @@ -571,7 +250,26 @@ static bool js_audio_AudioEngine_play2d(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC(js_audio_AudioEngine_play2d) -static bool js_audio_AudioEngine_getState(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_audio_AudioEngine_setLoop(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setLoop : Error processing arguments"); + cc::AudioEngine::setLoop(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_setLoop) + +static bool js_audio_AudioEngine_isLoop(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); size_t argc = args.size(); @@ -579,17 +277,86 @@ static bool js_audio_AudioEngine_getState(se::State& s) // NOLINT(readability-id if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getState : Error processing arguments"); - auto result = static_cast(cc::AudioEngine::getState(arg0.value())); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isLoop : Error processing arguments"); + bool result = cc::AudioEngine::isLoop(arg0.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getState : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isLoop : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC(js_audio_AudioEngine_getState) +SE_BIND_FUNC(js_audio_AudioEngine_isLoop) + +static bool js_audio_AudioEngine_setVolume(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setVolume : Error processing arguments"); + cc::AudioEngine::setVolume(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_setVolume) + +static bool js_audio_AudioEngine_getVolume(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getVolume : Error processing arguments"); + float result = cc::AudioEngine::getVolume(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getVolume : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_getVolume) + +static bool js_audio_AudioEngine_pause(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_pause : Error processing arguments"); + cc::AudioEngine::pause(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_pause) + +static bool js_audio_AudioEngine_pauseAll(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::AudioEngine::pauseAll(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_pauseAll) static bool js_audio_AudioEngine_resume(se::State& s) // NOLINT(readability-identifier-naming) { @@ -608,6 +375,19 @@ static bool js_audio_AudioEngine_resume(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC(js_audio_AudioEngine_resume) +static bool js_audio_AudioEngine_resumeAll(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::AudioEngine::resumeAll(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_resumeAll) + static bool js_audio_AudioEngine_stop(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -625,6 +405,61 @@ static bool js_audio_AudioEngine_stop(se::State& s) // NOLINT(readability-identi } SE_BIND_FUNC(js_audio_AudioEngine_stop) +static bool js_audio_AudioEngine_stopAll(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::AudioEngine::stopAll(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_stopAll) + +static bool js_audio_AudioEngine_setCurrentTime(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setCurrentTime : Error processing arguments"); + bool result = cc::AudioEngine::setCurrentTime(arg0.value(), arg1.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setCurrentTime : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_setCurrentTime) + +static bool js_audio_AudioEngine_getCurrentTime(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getCurrentTime : Error processing arguments"); + float result = cc::AudioEngine::getCurrentTime(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getCurrentTime : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_getCurrentTime) + static bool js_audio_AudioEngine_getDuration(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -645,41 +480,45 @@ static bool js_audio_AudioEngine_getDuration(se::State& s) // NOLINT(readability } SE_BIND_FUNC(js_audio_AudioEngine_getDuration) -static bool js_audio_AudioEngine_setLoop(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_audio_AudioEngine_getDurationFromFile(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; + if (argc == 1) { + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setLoop : Error processing arguments"); - cc::AudioEngine::setLoop(arg0.value(), arg1.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_audio_AudioEngine_setLoop) - -static bool js_audio_AudioEngine_getDefaultProfile(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::AudioProfile* result = cc::AudioEngine::getDefaultProfile(); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDurationFromFile : Error processing arguments"); + float result = cc::AudioEngine::getDurationFromFile(arg0.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDefaultProfile : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getDurationFromFile : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_FUNC(js_audio_AudioEngine_getDefaultProfile) +SE_BIND_FUNC(js_audio_AudioEngine_getDurationFromFile) + +static bool js_audio_AudioEngine_getState(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getState : Error processing arguments"); + auto result = static_cast(cc::AudioEngine::getState(arg0.value())); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getState : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_getState) static bool js_audio_AudioEngine_setFinishCallback(se::State& s) // NOLINT(readability-identifier-naming) { @@ -730,6 +569,73 @@ static bool js_audio_AudioEngine_setFinishCallback(se::State& s) // NOLINT(reada } SE_BIND_FUNC(js_audio_AudioEngine_setFinishCallback) +static bool js_audio_AudioEngine_getMaxAudioInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + int result = cc::AudioEngine::getMaxAudioInstance(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_getMaxAudioInstance : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_getMaxAudioInstance) + +static bool js_audio_AudioEngine_setMaxAudioInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setMaxAudioInstance : Error processing arguments"); + bool result = cc::AudioEngine::setMaxAudioInstance(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setMaxAudioInstance : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_setMaxAudioInstance) + +static bool js_audio_AudioEngine_uncache(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_uncache : Error processing arguments"); + cc::AudioEngine::uncache(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_uncache) + +static bool js_audio_AudioEngine_uncacheAll(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::AudioEngine::uncacheAll(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_uncacheAll) + static bool js_audio_AudioEngine_getProfile(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; @@ -764,6 +670,66 @@ static bool js_audio_AudioEngine_getProfile(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_audio_AudioEngine_getProfile) +static bool js_audio_AudioEngine_preload(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + do { + if (argc == 2) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + HolderType, true> arg1 = {}; + do { + if (args[1].isObject() && args[1].toObject()->isFunction()) + { + se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[1]); + jsFunc.toObject()->root(); + auto lambda = [=](bool larg0) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(1); + ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); + se::Value rval; + se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, &rval); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + arg1.data = lambda; + } + else + { + arg1.data = nullptr; + } + } while(false) + ; + if (!ok) { ok = true; break; } + cc::AudioEngine::preload(arg0.value(), arg1.value()); + return true; + } + } while (false); + do { + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + cc::AudioEngine::preload(arg0.value()); + return true; + } + } while (false); + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_preload) + static bool js_audio_AudioEngine_getPlayingAudioCount(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -781,6 +747,40 @@ static bool js_audio_AudioEngine_getPlayingAudioCount(se::State& s) // NOLINT(re } SE_BIND_FUNC(js_audio_AudioEngine_getPlayingAudioCount) +static bool js_audio_AudioEngine_setEnabled(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_setEnabled : Error processing arguments"); + cc::AudioEngine::setEnabled(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_setEnabled) + +static bool js_audio_AudioEngine_isEnabled(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + bool result = cc::AudioEngine::isEnabled(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_audio_AudioEngine_isEnabled : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_audio_AudioEngine_isEnabled) + bool js_register_audio_AudioEngine(se::Object* obj) // NOLINT(readability-identifier-naming) @@ -788,34 +788,34 @@ bool js_register_audio_AudioEngine(se::Object* obj) // NOLINT(readability-identi auto* cls = se::Class::create("AudioEngine", obj, nullptr, nullptr); cls->defineStaticFunction("lazyInit", _SE(js_audio_AudioEngine_lazyInit)); - cls->defineStaticFunction("setCurrentTime", _SE(js_audio_AudioEngine_setCurrentTime)); - cls->defineStaticFunction("getVolume", _SE(js_audio_AudioEngine_getVolume)); - cls->defineStaticFunction("uncache", _SE(js_audio_AudioEngine_uncache)); - cls->defineStaticFunction("resumeAll", _SE(js_audio_AudioEngine_resumeAll)); - cls->defineStaticFunction("stopAll", _SE(js_audio_AudioEngine_stopAll)); - cls->defineStaticFunction("pause", _SE(js_audio_AudioEngine_pause)); cls->defineStaticFunction("end", _SE(js_audio_AudioEngine_end)); - cls->defineStaticFunction("getMaxAudioInstance", _SE(js_audio_AudioEngine_getMaxAudioInstance)); - cls->defineStaticFunction("isEnabled", _SE(js_audio_AudioEngine_isEnabled)); - cls->defineStaticFunction("getDurationFromFile", _SE(js_audio_AudioEngine_getDurationFromFile)); - cls->defineStaticFunction("getCurrentTime", _SE(js_audio_AudioEngine_getCurrentTime)); - cls->defineStaticFunction("setMaxAudioInstance", _SE(js_audio_AudioEngine_setMaxAudioInstance)); - cls->defineStaticFunction("isLoop", _SE(js_audio_AudioEngine_isLoop)); - cls->defineStaticFunction("pauseAll", _SE(js_audio_AudioEngine_pauseAll)); - cls->defineStaticFunction("uncacheAll", _SE(js_audio_AudioEngine_uncacheAll)); - cls->defineStaticFunction("setVolume", _SE(js_audio_AudioEngine_setVolume)); - cls->defineStaticFunction("preload", _SE(js_audio_AudioEngine_preload)); - cls->defineStaticFunction("setEnabled", _SE(js_audio_AudioEngine_setEnabled)); - cls->defineStaticFunction("play2d", _SE(js_audio_AudioEngine_play2d)); - cls->defineStaticFunction("getState", _SE(js_audio_AudioEngine_getState)); - cls->defineStaticFunction("resume", _SE(js_audio_AudioEngine_resume)); - cls->defineStaticFunction("stop", _SE(js_audio_AudioEngine_stop)); - cls->defineStaticFunction("getDuration", _SE(js_audio_AudioEngine_getDuration)); - cls->defineStaticFunction("setLoop", _SE(js_audio_AudioEngine_setLoop)); cls->defineStaticFunction("getDefaultProfile", _SE(js_audio_AudioEngine_getDefaultProfile)); + cls->defineStaticFunction("play2d", _SE(js_audio_AudioEngine_play2d)); + cls->defineStaticFunction("setLoop", _SE(js_audio_AudioEngine_setLoop)); + cls->defineStaticFunction("isLoop", _SE(js_audio_AudioEngine_isLoop)); + cls->defineStaticFunction("setVolume", _SE(js_audio_AudioEngine_setVolume)); + cls->defineStaticFunction("getVolume", _SE(js_audio_AudioEngine_getVolume)); + cls->defineStaticFunction("pause", _SE(js_audio_AudioEngine_pause)); + cls->defineStaticFunction("pauseAll", _SE(js_audio_AudioEngine_pauseAll)); + cls->defineStaticFunction("resume", _SE(js_audio_AudioEngine_resume)); + cls->defineStaticFunction("resumeAll", _SE(js_audio_AudioEngine_resumeAll)); + cls->defineStaticFunction("stop", _SE(js_audio_AudioEngine_stop)); + cls->defineStaticFunction("stopAll", _SE(js_audio_AudioEngine_stopAll)); + cls->defineStaticFunction("setCurrentTime", _SE(js_audio_AudioEngine_setCurrentTime)); + cls->defineStaticFunction("getCurrentTime", _SE(js_audio_AudioEngine_getCurrentTime)); + cls->defineStaticFunction("getDuration", _SE(js_audio_AudioEngine_getDuration)); + cls->defineStaticFunction("getDurationFromFile", _SE(js_audio_AudioEngine_getDurationFromFile)); + cls->defineStaticFunction("getState", _SE(js_audio_AudioEngine_getState)); cls->defineStaticFunction("setFinishCallback", _SE(js_audio_AudioEngine_setFinishCallback)); + cls->defineStaticFunction("getMaxAudioInstance", _SE(js_audio_AudioEngine_getMaxAudioInstance)); + cls->defineStaticFunction("setMaxAudioInstance", _SE(js_audio_AudioEngine_setMaxAudioInstance)); + cls->defineStaticFunction("uncache", _SE(js_audio_AudioEngine_uncache)); + cls->defineStaticFunction("uncacheAll", _SE(js_audio_AudioEngine_uncacheAll)); cls->defineStaticFunction("getProfile", _SE(js_audio_AudioEngine_getProfile)); + cls->defineStaticFunction("preload", _SE(js_audio_AudioEngine_preload)); cls->defineStaticFunction("getPlayingAudioCount", _SE(js_audio_AudioEngine_getPlayingAudioCount)); + cls->defineStaticFunction("setEnabled", _SE(js_audio_AudioEngine_setEnabled)); + cls->defineStaticFunction("isEnabled", _SE(js_audio_AudioEngine_isEnabled)); cls->install(); JSBClassType::registerClass(cls); diff --git a/native/cocos/bindings/auto/jsb_audio_auto.h b/native/cocos/bindings/auto/jsb_audio_auto.h index bca7e300f4..f4a1eb72dd 100644 --- a/native/cocos/bindings/auto/jsb_audio_auto.h +++ b/native/cocos/bindings/auto/jsb_audio_auto.h @@ -23,33 +23,33 @@ bool register_all_audio(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::AudioEngine); SE_DECLARE_FUNC(js_audio_AudioEngine_lazyInit); -SE_DECLARE_FUNC(js_audio_AudioEngine_setCurrentTime); -SE_DECLARE_FUNC(js_audio_AudioEngine_getVolume); -SE_DECLARE_FUNC(js_audio_AudioEngine_uncache); -SE_DECLARE_FUNC(js_audio_AudioEngine_resumeAll); -SE_DECLARE_FUNC(js_audio_AudioEngine_stopAll); -SE_DECLARE_FUNC(js_audio_AudioEngine_pause); SE_DECLARE_FUNC(js_audio_AudioEngine_end); -SE_DECLARE_FUNC(js_audio_AudioEngine_getMaxAudioInstance); -SE_DECLARE_FUNC(js_audio_AudioEngine_isEnabled); -SE_DECLARE_FUNC(js_audio_AudioEngine_getDurationFromFile); -SE_DECLARE_FUNC(js_audio_AudioEngine_getCurrentTime); -SE_DECLARE_FUNC(js_audio_AudioEngine_setMaxAudioInstance); -SE_DECLARE_FUNC(js_audio_AudioEngine_isLoop); -SE_DECLARE_FUNC(js_audio_AudioEngine_pauseAll); -SE_DECLARE_FUNC(js_audio_AudioEngine_uncacheAll); -SE_DECLARE_FUNC(js_audio_AudioEngine_setVolume); -SE_DECLARE_FUNC(js_audio_AudioEngine_preload); -SE_DECLARE_FUNC(js_audio_AudioEngine_setEnabled); -SE_DECLARE_FUNC(js_audio_AudioEngine_play2d); -SE_DECLARE_FUNC(js_audio_AudioEngine_getState); -SE_DECLARE_FUNC(js_audio_AudioEngine_resume); -SE_DECLARE_FUNC(js_audio_AudioEngine_stop); -SE_DECLARE_FUNC(js_audio_AudioEngine_getDuration); -SE_DECLARE_FUNC(js_audio_AudioEngine_setLoop); SE_DECLARE_FUNC(js_audio_AudioEngine_getDefaultProfile); +SE_DECLARE_FUNC(js_audio_AudioEngine_play2d); +SE_DECLARE_FUNC(js_audio_AudioEngine_setLoop); +SE_DECLARE_FUNC(js_audio_AudioEngine_isLoop); +SE_DECLARE_FUNC(js_audio_AudioEngine_setVolume); +SE_DECLARE_FUNC(js_audio_AudioEngine_getVolume); +SE_DECLARE_FUNC(js_audio_AudioEngine_pause); +SE_DECLARE_FUNC(js_audio_AudioEngine_pauseAll); +SE_DECLARE_FUNC(js_audio_AudioEngine_resume); +SE_DECLARE_FUNC(js_audio_AudioEngine_resumeAll); +SE_DECLARE_FUNC(js_audio_AudioEngine_stop); +SE_DECLARE_FUNC(js_audio_AudioEngine_stopAll); +SE_DECLARE_FUNC(js_audio_AudioEngine_setCurrentTime); +SE_DECLARE_FUNC(js_audio_AudioEngine_getCurrentTime); +SE_DECLARE_FUNC(js_audio_AudioEngine_getDuration); +SE_DECLARE_FUNC(js_audio_AudioEngine_getDurationFromFile); +SE_DECLARE_FUNC(js_audio_AudioEngine_getState); SE_DECLARE_FUNC(js_audio_AudioEngine_setFinishCallback); +SE_DECLARE_FUNC(js_audio_AudioEngine_getMaxAudioInstance); +SE_DECLARE_FUNC(js_audio_AudioEngine_setMaxAudioInstance); +SE_DECLARE_FUNC(js_audio_AudioEngine_uncache); +SE_DECLARE_FUNC(js_audio_AudioEngine_uncacheAll); SE_DECLARE_FUNC(js_audio_AudioEngine_getProfile); +SE_DECLARE_FUNC(js_audio_AudioEngine_preload); SE_DECLARE_FUNC(js_audio_AudioEngine_getPlayingAudioCount); +SE_DECLARE_FUNC(js_audio_AudioEngine_setEnabled); +SE_DECLARE_FUNC(js_audio_AudioEngine_isEnabled); #endif //#if (USE_AUDIO > 0) diff --git a/native/cocos/bindings/auto/jsb_cocos_auto.cpp b/native/cocos/bindings/auto/jsb_cocos_auto.cpp index 466882ff64..3354c5b4fc 100644 --- a/native/cocos/bindings/auto/jsb_cocos_auto.cpp +++ b/native/cocos/bindings/auto/jsb_cocos_auto.cpp @@ -739,6 +739,40 @@ static bool js_engine_FileUtils_writeValueVectorToFile(se::State& s) // NOLINT(r } SE_BIND_FUNC(js_engine_FileUtils_writeValueVectorToFile) +static bool js_engine_FileUtils_getInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::FileUtils* result = cc::FileUtils::getInstance(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_engine_FileUtils_getInstance : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_engine_FileUtils_getInstance) + +static bool js_engine_FileUtils_setDelegate(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_engine_FileUtils_setDelegate : Error processing arguments"); + cc::FileUtils::setDelegate(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_engine_FileUtils_setDelegate) + static bool js_engine_FileUtils_normalizePath(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -759,40 +793,6 @@ static bool js_engine_FileUtils_normalizePath(se::State& s) // NOLINT(readabilit } SE_BIND_FUNC(js_engine_FileUtils_normalizePath) -static bool js_engine_FileUtils_setDelegate(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_engine_FileUtils_setDelegate : Error processing arguments"); - cc::FileUtils::setDelegate(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_engine_FileUtils_setDelegate) - -static bool js_engine_FileUtils_getInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::FileUtils* result = cc::FileUtils::getInstance(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_engine_FileUtils_getInstance : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_engine_FileUtils_getInstance) - static bool js_engine_FileUtils_getFileDir(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -863,9 +863,9 @@ bool js_register_engine_FileUtils(se::Object* obj) // NOLINT(readability-identif cls->defineFunction("writeToFile", _SE(js_engine_FileUtils_writeToFile)); cls->defineFunction("writeValueMapToFile", _SE(js_engine_FileUtils_writeValueMapToFile)); cls->defineFunction("writeValueVectorToFile", _SE(js_engine_FileUtils_writeValueVectorToFile)); - cls->defineStaticFunction("normalizePath", _SE(js_engine_FileUtils_normalizePath)); - cls->defineStaticFunction("setDelegate", _SE(js_engine_FileUtils_setDelegate)); cls->defineStaticFunction("getInstance", _SE(js_engine_FileUtils_getInstance)); + cls->defineStaticFunction("setDelegate", _SE(js_engine_FileUtils_setDelegate)); + cls->defineStaticFunction("normalizePath", _SE(js_engine_FileUtils_normalizePath)); cls->defineStaticFunction("getFileDir", _SE(js_engine_FileUtils_getFileDir)); cls->defineFinalizeFunction(_SE(js_cc_FileUtils_finalize)); cls->install(); @@ -1547,17 +1547,17 @@ bool js_register_engine_CanvasRenderingContext2D(se::Object* obj) // NOLINT(read { auto* cls = se::Class::create("CanvasRenderingContext2D", obj, nullptr, _SE(js_engine_CanvasRenderingContext2D_constructor)); - cls->defineProperty("strokeStyle", nullptr, _SE(js_engine_CanvasRenderingContext2D_setStrokeStyle)); - cls->defineProperty("lineWidth", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineWidth)); - cls->defineProperty("lineCap", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineCap)); - cls->defineProperty("globalCompositeOperation", nullptr, _SE(js_engine_CanvasRenderingContext2D_setGlobalCompositeOperation)); - cls->defineProperty("fillStyle", nullptr, _SE(js_engine_CanvasRenderingContext2D_setFillStyle)); - cls->defineProperty("height", nullptr, _SE(js_engine_CanvasRenderingContext2D_setHeight)); cls->defineProperty("width", nullptr, _SE(js_engine_CanvasRenderingContext2D_setWidth)); - cls->defineProperty("textBaseline", nullptr, _SE(js_engine_CanvasRenderingContext2D_setTextBaseline)); - cls->defineProperty("lineJoin", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineJoin)); + cls->defineProperty("height", nullptr, _SE(js_engine_CanvasRenderingContext2D_setHeight)); + cls->defineProperty("fillStyle", nullptr, _SE(js_engine_CanvasRenderingContext2D_setFillStyle)); cls->defineProperty("font", nullptr, _SE(js_engine_CanvasRenderingContext2D_setFont)); + cls->defineProperty("globalCompositeOperation", nullptr, _SE(js_engine_CanvasRenderingContext2D_setGlobalCompositeOperation)); + cls->defineProperty("lineCap", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineCap)); + cls->defineProperty("lineJoin", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineJoin)); + cls->defineProperty("lineWidth", nullptr, _SE(js_engine_CanvasRenderingContext2D_setLineWidth)); + cls->defineProperty("strokeStyle", nullptr, _SE(js_engine_CanvasRenderingContext2D_setStrokeStyle)); cls->defineProperty("textAlign", nullptr, _SE(js_engine_CanvasRenderingContext2D_setTextAlign)); + cls->defineProperty("textBaseline", nullptr, _SE(js_engine_CanvasRenderingContext2D_setTextBaseline)); cls->defineFunction("beginPath", _SE(js_engine_CanvasRenderingContext2D_beginPath)); cls->defineFunction("clearRect", _SE(js_engine_CanvasRenderingContext2D_clearRect)); cls->defineFunction("closePath", _SE(js_engine_CanvasRenderingContext2D_closePath)); @@ -1588,6 +1588,23 @@ bool js_register_engine_CanvasRenderingContext2D(se::Object* obj) // NOLINT(read se::Object* __jsb_cc_Device_proto = nullptr; se::Class* __jsb_cc_Device_class = nullptr; +static bool js_engine_Device_getDPI(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + int result = cc::Device::getDPI(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_engine_Device_getDPI : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_engine_Device_getDPI) + static bool js_engine_Device_getDevicePixelRatio(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -1639,74 +1656,6 @@ static bool js_engine_Device_setAccelerometerInterval(se::State& s) // NOLINT(re } SE_BIND_FUNC(js_engine_Device_setAccelerometerInterval) -static bool js_engine_Device_vibrate(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_engine_Device_vibrate : Error processing arguments"); - cc::Device::vibrate(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_engine_Device_vibrate) - -static bool js_engine_Device_setKeepScreenOn(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_engine_Device_setKeepScreenOn : Error processing arguments"); - cc::Device::setKeepScreenOn(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_engine_Device_setKeepScreenOn) - -static bool js_engine_Device_getNetworkType(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cc::Device::getNetworkType()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_engine_Device_getNetworkType : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_engine_Device_getNetworkType) - -static bool js_engine_Device_getBatteryLevel(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - float result = cc::Device::getBatteryLevel(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_engine_Device_getBatteryLevel : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_engine_Device_getBatteryLevel) - static bool js_engine_Device_getDeviceOrientation(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -1724,40 +1673,6 @@ static bool js_engine_Device_getDeviceOrientation(se::State& s) // NOLINT(readab } SE_BIND_FUNC(js_engine_Device_getDeviceOrientation) -static bool js_engine_Device_getDPI(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - int result = cc::Device::getDPI(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_engine_Device_getDPI : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_engine_Device_getDPI) - -static bool js_engine_Device_getSafeAreaEdge(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::Vec4 result = cc::Device::getSafeAreaEdge(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_engine_Device_getSafeAreaEdge : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_engine_Device_getSafeAreaEdge) - static bool js_engine_Device_getDeviceModel(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -1775,23 +1690,108 @@ static bool js_engine_Device_getDeviceModel(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_engine_Device_getDeviceModel) +static bool js_engine_Device_setKeepScreenOn(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_engine_Device_setKeepScreenOn : Error processing arguments"); + cc::Device::setKeepScreenOn(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_engine_Device_setKeepScreenOn) + +static bool js_engine_Device_vibrate(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_engine_Device_vibrate : Error processing arguments"); + cc::Device::vibrate(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_engine_Device_vibrate) + +static bool js_engine_Device_getBatteryLevel(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + float result = cc::Device::getBatteryLevel(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_engine_Device_getBatteryLevel : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_engine_Device_getBatteryLevel) + +static bool js_engine_Device_getNetworkType(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + auto result = static_cast(cc::Device::getNetworkType()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_engine_Device_getNetworkType : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_engine_Device_getNetworkType) + +static bool js_engine_Device_getSafeAreaEdge(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::Vec4 result = cc::Device::getSafeAreaEdge(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_engine_Device_getSafeAreaEdge : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_engine_Device_getSafeAreaEdge) + bool js_register_engine_Device(se::Object* obj) // NOLINT(readability-identifier-naming) { auto* cls = se::Class::create("Device", obj, nullptr, nullptr); + cls->defineStaticFunction("getDPI", _SE(js_engine_Device_getDPI)); cls->defineStaticFunction("getDevicePixelRatio", _SE(js_engine_Device_getDevicePixelRatio)); cls->defineStaticFunction("setAccelerometerEnabled", _SE(js_engine_Device_setAccelerometerEnabled)); cls->defineStaticFunction("setAccelerometerInterval", _SE(js_engine_Device_setAccelerometerInterval)); - cls->defineStaticFunction("vibrate", _SE(js_engine_Device_vibrate)); - cls->defineStaticFunction("setKeepScreenOn", _SE(js_engine_Device_setKeepScreenOn)); - cls->defineStaticFunction("getNetworkType", _SE(js_engine_Device_getNetworkType)); - cls->defineStaticFunction("getBatteryLevel", _SE(js_engine_Device_getBatteryLevel)); cls->defineStaticFunction("getDeviceOrientation", _SE(js_engine_Device_getDeviceOrientation)); - cls->defineStaticFunction("getDPI", _SE(js_engine_Device_getDPI)); - cls->defineStaticFunction("getSafeAreaEdge", _SE(js_engine_Device_getSafeAreaEdge)); cls->defineStaticFunction("getDeviceModel", _SE(js_engine_Device_getDeviceModel)); + cls->defineStaticFunction("setKeepScreenOn", _SE(js_engine_Device_setKeepScreenOn)); + cls->defineStaticFunction("vibrate", _SE(js_engine_Device_vibrate)); + cls->defineStaticFunction("getBatteryLevel", _SE(js_engine_Device_getBatteryLevel)); + cls->defineStaticFunction("getNetworkType", _SE(js_engine_Device_getNetworkType)); + cls->defineStaticFunction("getSafeAreaEdge", _SE(js_engine_Device_getSafeAreaEdge)); cls->install(); JSBClassType::registerClass(cls); @@ -1855,9 +1855,9 @@ bool register_all_engine(se::Object* obj) se::Object* ns = nsVal.toObject(); js_register_engine_FileUtils(ns); - js_register_engine_Device(ns); js_register_engine_CanvasGradient(ns); js_register_engine_CanvasRenderingContext2D(ns); + js_register_engine_Device(ns); js_register_engine_SAXParser(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_cocos_auto.h b/native/cocos/bindings/auto/jsb_cocos_auto.h index 2721b5187d..66a55ee430 100644 --- a/native/cocos/bindings/auto/jsb_cocos_auto.h +++ b/native/cocos/bindings/auto/jsb_cocos_auto.h @@ -47,9 +47,9 @@ SE_DECLARE_FUNC(js_engine_FileUtils_writeStringToFile); SE_DECLARE_FUNC(js_engine_FileUtils_writeToFile); SE_DECLARE_FUNC(js_engine_FileUtils_writeValueMapToFile); SE_DECLARE_FUNC(js_engine_FileUtils_writeValueVectorToFile); -SE_DECLARE_FUNC(js_engine_FileUtils_normalizePath); -SE_DECLARE_FUNC(js_engine_FileUtils_setDelegate); SE_DECLARE_FUNC(js_engine_FileUtils_getInstance); +SE_DECLARE_FUNC(js_engine_FileUtils_setDelegate); +SE_DECLARE_FUNC(js_engine_FileUtils_normalizePath); SE_DECLARE_FUNC(js_engine_FileUtils_getFileDir); extern se::Object* __jsb_cc_CanvasGradient_proto; @@ -95,17 +95,17 @@ bool js_register_cc_Device(se::Object* obj); bool register_all_engine(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::Device); +SE_DECLARE_FUNC(js_engine_Device_getDPI); SE_DECLARE_FUNC(js_engine_Device_getDevicePixelRatio); SE_DECLARE_FUNC(js_engine_Device_setAccelerometerEnabled); SE_DECLARE_FUNC(js_engine_Device_setAccelerometerInterval); -SE_DECLARE_FUNC(js_engine_Device_vibrate); -SE_DECLARE_FUNC(js_engine_Device_setKeepScreenOn); -SE_DECLARE_FUNC(js_engine_Device_getNetworkType); -SE_DECLARE_FUNC(js_engine_Device_getBatteryLevel); SE_DECLARE_FUNC(js_engine_Device_getDeviceOrientation); -SE_DECLARE_FUNC(js_engine_Device_getDPI); -SE_DECLARE_FUNC(js_engine_Device_getSafeAreaEdge); SE_DECLARE_FUNC(js_engine_Device_getDeviceModel); +SE_DECLARE_FUNC(js_engine_Device_setKeepScreenOn); +SE_DECLARE_FUNC(js_engine_Device_vibrate); +SE_DECLARE_FUNC(js_engine_Device_getBatteryLevel); +SE_DECLARE_FUNC(js_engine_Device_getNetworkType); +SE_DECLARE_FUNC(js_engine_Device_getSafeAreaEdge); extern se::Object* __jsb_cc_SAXParser_proto; extern se::Class* __jsb_cc_SAXParser_class; diff --git a/native/cocos/bindings/auto/jsb_dragonbones_auto.cpp b/native/cocos/bindings/auto/jsb_dragonbones_auto.cpp index 3f4ff4ec22..c88dfd71d1 100644 --- a/native/cocos/bindings/auto/jsb_dragonbones_auto.cpp +++ b/native/cocos/bindings/auto/jsb_dragonbones_auto.cpp @@ -29,6 +29,25 @@ static bool js_dragonbones_BaseObject_returnToPool(se::State& s) // NOLINT(reada } SE_BIND_FUNC(js_dragonbones_BaseObject_returnToPool) +static bool js_dragonbones_BaseObject_setMaxCount(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "js_dragonbones_BaseObject_setMaxCount : Error processing arguments"); + dragonBones::BaseObject::setMaxCount(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_dragonbones_BaseObject_setMaxCount) + static bool js_dragonbones_BaseObject_clearPool(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -50,25 +69,6 @@ static bool js_dragonbones_BaseObject_clearPool(se::State& s) // NOLINT(readabil } SE_BIND_FUNC(js_dragonbones_BaseObject_clearPool) -static bool js_dragonbones_BaseObject_setMaxCount(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - SE_PRECONDITION2(ok, false, "js_dragonbones_BaseObject_setMaxCount : Error processing arguments"); - dragonBones::BaseObject::setMaxCount(arg0.value(), arg1.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_dragonbones_BaseObject_setMaxCount) - bool js_register_dragonbones_BaseObject(se::Object* obj) // NOLINT(readability-identifier-naming) @@ -76,8 +76,8 @@ bool js_register_dragonbones_BaseObject(se::Object* obj) // NOLINT(readability-i auto* cls = se::Class::create("BaseObject", obj, nullptr, nullptr); cls->defineFunction("returnToPool", _SE(js_dragonbones_BaseObject_returnToPool)); - cls->defineStaticFunction("clearPool", _SE(js_dragonbones_BaseObject_clearPool)); cls->defineStaticFunction("setMaxCount", _SE(js_dragonbones_BaseObject_setMaxCount)); + cls->defineStaticFunction("clearPool", _SE(js_dragonbones_BaseObject_clearPool)); cls->install(); JSBClassType::registerClass(cls); @@ -6049,19 +6049,6 @@ static bool js_dragonbones_ArmatureCacheMgr_removeArmatureCache(se::State& s) // } SE_BIND_FUNC(js_dragonbones_ArmatureCacheMgr_removeArmatureCache) -static bool js_dragonbones_ArmatureCacheMgr_destroyInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - dragonBones::ArmatureCacheMgr::destroyInstance(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_dragonbones_ArmatureCacheMgr_destroyInstance) - static bool js_dragonbones_ArmatureCacheMgr_getInstance(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -6079,6 +6066,19 @@ static bool js_dragonbones_ArmatureCacheMgr_getInstance(se::State& s) // NOLINT( } SE_BIND_FUNC(js_dragonbones_ArmatureCacheMgr_getInstance) +static bool js_dragonbones_ArmatureCacheMgr_destroyInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + dragonBones::ArmatureCacheMgr::destroyInstance(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_dragonbones_ArmatureCacheMgr_destroyInstance) + static bool js_dragonBones_ArmatureCacheMgr_finalize(se::State& s) // NOLINT(readability-identifier-naming) { @@ -6099,8 +6099,8 @@ bool js_register_dragonbones_ArmatureCacheMgr(se::Object* obj) // NOLINT(readabi cls->defineFunction("buildArmatureCache", _SE(js_dragonbones_ArmatureCacheMgr_buildArmatureCache)); cls->defineFunction("removeArmatureCache", _SE(js_dragonbones_ArmatureCacheMgr_removeArmatureCache)); - cls->defineStaticFunction("destroyInstance", _SE(js_dragonbones_ArmatureCacheMgr_destroyInstance)); cls->defineStaticFunction("getInstance", _SE(js_dragonbones_ArmatureCacheMgr_getInstance)); + cls->defineStaticFunction("destroyInstance", _SE(js_dragonbones_ArmatureCacheMgr_destroyInstance)); cls->defineFinalizeFunction(_SE(js_dragonBones_ArmatureCacheMgr_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -7026,19 +7026,6 @@ static bool js_dragonbones_CCFactory_isInit(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_dragonbones_CCFactory_isInit) -static bool js_dragonbones_CCFactory_destroyFactory(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - dragonBones::CCFactory::destroyFactory(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_dragonbones_CCFactory_destroyFactory) - static bool js_dragonbones_CCFactory_getFactory(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -7056,6 +7043,19 @@ static bool js_dragonbones_CCFactory_getFactory(se::State& s) // NOLINT(readabil } SE_BIND_FUNC(js_dragonbones_CCFactory_getFactory) +static bool js_dragonbones_CCFactory_destroyFactory(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + dragonBones::CCFactory::destroyFactory(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_dragonbones_CCFactory_destroyFactory) + static bool js_dragonbones_CCFactory_getClock(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -7118,8 +7118,8 @@ bool js_register_dragonbones_CCFactory(se::Object* obj) // NOLINT(readability-id cls->defineFunction("stopSchedule", _SE(js_dragonbones_CCFactory_stopSchedule)); cls->defineFunction("update", _SE(js_dragonbones_CCFactory_update)); cls->defineStaticFunction("isInit", _SE(js_dragonbones_CCFactory_isInit)); - cls->defineStaticFunction("destroyFactory", _SE(js_dragonbones_CCFactory_destroyFactory)); cls->defineStaticFunction("getFactory", _SE(js_dragonbones_CCFactory_getFactory)); + cls->defineStaticFunction("destroyFactory", _SE(js_dragonbones_CCFactory_destroyFactory)); cls->defineStaticFunction("getClock", _SE(js_dragonbones_CCFactory_getClock)); cls->defineFinalizeFunction(_SE(js_dragonBones_CCFactory_finalize)); cls->install(); @@ -7180,33 +7180,33 @@ bool register_all_dragonbones(se::Object* obj) se::Object* ns = nsVal.toObject(); js_register_dragonbones_BaseObject(ns); - js_register_dragonbones_TransformObject(ns); - js_register_dragonbones_Slot(ns); + js_register_dragonbones_Rectangle(ns); js_register_dragonbones_Matrix(ns); js_register_dragonbones_Transform(ns); - js_register_dragonbones_Animation(ns); - js_register_dragonbones_TextureData(ns); - js_register_dragonbones_CCTextureData(ns); - js_register_dragonbones_BaseFactory(ns); - js_register_dragonbones_CCFactory(ns); - js_register_dragonbones_WorldClock(ns); - js_register_dragonbones_Rectangle(ns); js_register_dragonbones_TextureAtlasData(ns); - js_register_dragonbones_CCArmatureDisplay(ns); - js_register_dragonbones_AnimationState(ns); - js_register_dragonbones_BoneData(ns); + js_register_dragonbones_TextureData(ns); js_register_dragonbones_ArmatureData(ns); - js_register_dragonbones_CCTextureAtlasData(ns); - js_register_dragonbones_CCSlot(ns); - js_register_dragonbones_Armature(ns); - js_register_dragonbones_Bone(ns); - js_register_dragonbones_ArmatureCacheMgr(ns); - js_register_dragonbones_SkinData(ns); - js_register_dragonbones_EventObject(ns); + js_register_dragonbones_BoneData(ns); js_register_dragonbones_SlotData(ns); js_register_dragonbones_DragonBonesData(ns); + js_register_dragonbones_SkinData(ns); js_register_dragonbones_AnimationData(ns); + js_register_dragonbones_Armature(ns); + js_register_dragonbones_TransformObject(ns); + js_register_dragonbones_AnimationState(ns); + js_register_dragonbones_Bone(ns); + js_register_dragonbones_Slot(ns); + js_register_dragonbones_WorldClock(ns); + js_register_dragonbones_Animation(ns); + js_register_dragonbones_EventObject(ns); + js_register_dragonbones_BaseFactory(ns); + js_register_dragonbones_CCSlot(ns); + js_register_dragonbones_CCArmatureDisplay(ns); + js_register_dragonbones_ArmatureCacheMgr(ns); js_register_dragonbones_CCArmatureCacheDisplay(ns); + js_register_dragonbones_CCFactory(ns); + js_register_dragonbones_CCTextureAtlasData(ns); + js_register_dragonbones_CCTextureData(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_dragonbones_auto.h b/native/cocos/bindings/auto/jsb_dragonbones_auto.h index 1e03c56c6d..a78f747f96 100644 --- a/native/cocos/bindings/auto/jsb_dragonbones_auto.h +++ b/native/cocos/bindings/auto/jsb_dragonbones_auto.h @@ -14,8 +14,8 @@ bool register_all_dragonbones(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(dragonBones::BaseObject); SE_DECLARE_FUNC(js_dragonbones_BaseObject_returnToPool); -SE_DECLARE_FUNC(js_dragonbones_BaseObject_clearPool); SE_DECLARE_FUNC(js_dragonbones_BaseObject_setMaxCount); +SE_DECLARE_FUNC(js_dragonbones_BaseObject_clearPool); extern se::Object* __jsb_dragonBones_Rectangle_proto; extern se::Class* __jsb_dragonBones_Rectangle_class; @@ -389,8 +389,8 @@ bool register_all_dragonbones(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(dragonBones::ArmatureCacheMgr); SE_DECLARE_FUNC(js_dragonbones_ArmatureCacheMgr_buildArmatureCache); SE_DECLARE_FUNC(js_dragonbones_ArmatureCacheMgr_removeArmatureCache); -SE_DECLARE_FUNC(js_dragonbones_ArmatureCacheMgr_destroyInstance); SE_DECLARE_FUNC(js_dragonbones_ArmatureCacheMgr_getInstance); +SE_DECLARE_FUNC(js_dragonbones_ArmatureCacheMgr_destroyInstance); extern se::Object* __jsb_dragonBones_CCArmatureCacheDisplay_proto; extern se::Class* __jsb_dragonBones_CCArmatureCacheDisplay_class; @@ -447,8 +447,8 @@ SE_DECLARE_FUNC(js_dragonbones_CCFactory_setTimeScale); SE_DECLARE_FUNC(js_dragonbones_CCFactory_stopSchedule); SE_DECLARE_FUNC(js_dragonbones_CCFactory_update); SE_DECLARE_FUNC(js_dragonbones_CCFactory_isInit); -SE_DECLARE_FUNC(js_dragonbones_CCFactory_destroyFactory); SE_DECLARE_FUNC(js_dragonbones_CCFactory_getFactory); +SE_DECLARE_FUNC(js_dragonbones_CCFactory_destroyFactory); SE_DECLARE_FUNC(js_dragonbones_CCFactory_getClock); SE_DECLARE_FUNC(js_dragonbones_CCFactory_CCFactory); diff --git a/native/cocos/bindings/auto/jsb_editor_support_auto.cpp b/native/cocos/bindings/auto/jsb_editor_support_auto.cpp index 1c9f92663f..ca19de70b0 100644 --- a/native/cocos/bindings/auto/jsb_editor_support_auto.cpp +++ b/native/cocos/bindings/auto/jsb_editor_support_auto.cpp @@ -532,6 +532,23 @@ static bool js_editor_support_MiddlewareManager_update(se::State& s) // NOLINT(r } SE_BIND_FUNC(js_editor_support_MiddlewareManager_update) +static bool js_editor_support_MiddlewareManager_getInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::middleware::MiddlewareManager* result = cc::middleware::MiddlewareManager::getInstance(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_editor_support_MiddlewareManager_getInstance : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_editor_support_MiddlewareManager_getInstance) + static bool js_editor_support_MiddlewareManager_destroyInstance(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -562,23 +579,6 @@ static bool js_editor_support_MiddlewareManager_generateModuleID(se::State& s) / } SE_BIND_FUNC(js_editor_support_MiddlewareManager_generateModuleID) -static bool js_editor_support_MiddlewareManager_getInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::middleware::MiddlewareManager* result = cc::middleware::MiddlewareManager::getInstance(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_editor_support_MiddlewareManager_getInstance : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_editor_support_MiddlewareManager_getInstance) - SE_DECLARE_FINALIZE_FUNC(js_cc_middleware_MiddlewareManager_finalize) static bool js_editor_support_MiddlewareManager_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c @@ -618,9 +618,9 @@ bool js_register_editor_support_MiddlewareManager(se::Object* obj) // NOLINT(rea cls->defineFunction("getVBTypedArrayLength", _SE(js_editor_support_MiddlewareManager_getVBTypedArrayLength)); cls->defineFunction("render", _SE(js_editor_support_MiddlewareManager_render)); cls->defineFunction("update", _SE(js_editor_support_MiddlewareManager_update)); + cls->defineStaticFunction("getInstance", _SE(js_editor_support_MiddlewareManager_getInstance)); cls->defineStaticFunction("destroyInstance", _SE(js_editor_support_MiddlewareManager_destroyInstance)); cls->defineStaticFunction("generateModuleID", _SE(js_editor_support_MiddlewareManager_generateModuleID)); - cls->defineStaticFunction("getInstance", _SE(js_editor_support_MiddlewareManager_getInstance)); cls->defineFinalizeFunction(_SE(js_cc_middleware_MiddlewareManager_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -643,9 +643,9 @@ bool register_all_editor_support(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_editor_support_MiddlewareManager(ns); - js_register_editor_support_SharedBufferManager(ns); js_register_editor_support_Texture2D(ns); + js_register_editor_support_SharedBufferManager(ns); + js_register_editor_support_MiddlewareManager(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_editor_support_auto.h b/native/cocos/bindings/auto/jsb_editor_support_auto.h index a59289ad2d..1e53355af5 100644 --- a/native/cocos/bindings/auto/jsb_editor_support_auto.h +++ b/native/cocos/bindings/auto/jsb_editor_support_auto.h @@ -50,8 +50,8 @@ SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_getVBTypedArray); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_getVBTypedArrayLength); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_render); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_update); +SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_getInstance); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_destroyInstance); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_generateModuleID); -SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_getInstance); SE_DECLARE_FUNC(js_editor_support_MiddlewareManager_MiddlewareManager); diff --git a/native/cocos/bindings/auto/jsb_extension_auto.cpp b/native/cocos/bindings/auto/jsb_extension_auto.cpp index e0f3367ab4..e233425cc4 100644 --- a/native/cocos/bindings/auto/jsb_extension_auto.cpp +++ b/native/cocos/bindings/auto/jsb_extension_auto.cpp @@ -1273,9 +1273,9 @@ bool register_all_extension(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_extension_AssetsManagerEx(ns); js_register_extension_EventAssetsManagerEx(ns); js_register_extension_Manifest(ns); + js_register_extension_AssetsManagerEx(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_gfx_auto.cpp b/native/cocos/bindings/auto/jsb_gfx_auto.cpp index 474249d528..ef474a3c9d 100644 --- a/native/cocos/bindings/auto/jsb_gfx_auto.cpp +++ b/native/cocos/bindings/auto/jsb_gfx_auto.cpp @@ -566,60 +566,6 @@ static bool js_gfx_DeviceCaps_set_maxCubeMapTextureSize(se::State& s) // NOLINT( } SE_BIND_PROP_SET(js_gfx_DeviceCaps_set_maxCubeMapTextureSize) -static bool js_gfx_DeviceCaps_get_depthBits(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceCaps_get_depthBits : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->depthBits, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->depthBits, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceCaps_get_depthBits) - -static bool js_gfx_DeviceCaps_set_depthBits(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceCaps_set_depthBits : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->depthBits, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceCaps_set_depthBits : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceCaps_set_depthBits) - -static bool js_gfx_DeviceCaps_get_stencilBits(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceCaps_get_stencilBits : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->stencilBits, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->stencilBits, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceCaps_get_stencilBits) - -static bool js_gfx_DeviceCaps_set_stencilBits(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceCaps_set_stencilBits : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->stencilBits, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceCaps_set_stencilBits : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceCaps_set_stencilBits) - static bool js_gfx_DeviceCaps_get_uboOffsetAlignment(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -901,14 +847,6 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::DeviceCaps * to, se::Obje if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->maxCubeMapTextureSize), ctx); } - json->getProperty("depthBits", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->depthBits), ctx); - } - json->getProperty("stencilBits", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->stencilBits), ctx); - } json->getProperty("uboOffsetAlignment", &field); if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->uboOffsetAlignment), ctx); @@ -1019,34 +957,28 @@ static bool js_gfx_DeviceCaps_constructor(se::State& s) // NOLINT(readability-id ok &= sevalue_to_native(args[12], &(cobj->maxCubeMapTextureSize), nullptr); } if (argc > 13 && !args[13].isUndefined()) { - ok &= sevalue_to_native(args[13], &(cobj->depthBits), nullptr); + ok &= sevalue_to_native(args[13], &(cobj->uboOffsetAlignment), nullptr); } if (argc > 14 && !args[14].isUndefined()) { - ok &= sevalue_to_native(args[14], &(cobj->stencilBits), nullptr); + ok &= sevalue_to_native(args[14], &(cobj->maxComputeSharedMemorySize), nullptr); } if (argc > 15 && !args[15].isUndefined()) { - ok &= sevalue_to_native(args[15], &(cobj->uboOffsetAlignment), nullptr); + ok &= sevalue_to_native(args[15], &(cobj->maxComputeWorkGroupInvocations), nullptr); } if (argc > 16 && !args[16].isUndefined()) { - ok &= sevalue_to_native(args[16], &(cobj->maxComputeSharedMemorySize), nullptr); + ok &= sevalue_to_native(args[16], &(cobj->maxComputeWorkGroupSize), nullptr); } if (argc > 17 && !args[17].isUndefined()) { - ok &= sevalue_to_native(args[17], &(cobj->maxComputeWorkGroupInvocations), nullptr); + ok &= sevalue_to_native(args[17], &(cobj->maxComputeWorkGroupCount), nullptr); } if (argc > 18 && !args[18].isUndefined()) { - ok &= sevalue_to_native(args[18], &(cobj->maxComputeWorkGroupSize), nullptr); + ok &= sevalue_to_native(args[18], &(cobj->clipSpaceMinZ), nullptr); } if (argc > 19 && !args[19].isUndefined()) { - ok &= sevalue_to_native(args[19], &(cobj->maxComputeWorkGroupCount), nullptr); + ok &= sevalue_to_native(args[19], &(cobj->screenSpaceSignY), nullptr); } if (argc > 20 && !args[20].isUndefined()) { - ok &= sevalue_to_native(args[20], &(cobj->clipSpaceMinZ), nullptr); - } - if (argc > 21 && !args[21].isUndefined()) { - ok &= sevalue_to_native(args[21], &(cobj->screenSpaceSignY), nullptr); - } - if (argc > 22 && !args[22].isUndefined()) { - ok &= sevalue_to_native(args[22], &(cobj->clipSpaceSignY), nullptr); + ok &= sevalue_to_native(args[20], &(cobj->clipSpaceSignY), nullptr); } if(!ok) { @@ -1093,8 +1025,6 @@ bool js_register_gfx_DeviceCaps(se::Object* obj) // NOLINT(readability-identifie cls->defineProperty("maxUniformBlockSize", _SE(js_gfx_DeviceCaps_get_maxUniformBlockSize), _SE(js_gfx_DeviceCaps_set_maxUniformBlockSize)); cls->defineProperty("maxTextureSize", _SE(js_gfx_DeviceCaps_get_maxTextureSize), _SE(js_gfx_DeviceCaps_set_maxTextureSize)); cls->defineProperty("maxCubeMapTextureSize", _SE(js_gfx_DeviceCaps_get_maxCubeMapTextureSize), _SE(js_gfx_DeviceCaps_set_maxCubeMapTextureSize)); - cls->defineProperty("depthBits", _SE(js_gfx_DeviceCaps_get_depthBits), _SE(js_gfx_DeviceCaps_set_depthBits)); - cls->defineProperty("stencilBits", _SE(js_gfx_DeviceCaps_get_stencilBits), _SE(js_gfx_DeviceCaps_set_stencilBits)); cls->defineProperty("uboOffsetAlignment", _SE(js_gfx_DeviceCaps_get_uboOffsetAlignment), _SE(js_gfx_DeviceCaps_set_uboOffsetAlignment)); cls->defineProperty("maxComputeSharedMemorySize", _SE(js_gfx_DeviceCaps_get_maxComputeSharedMemorySize), _SE(js_gfx_DeviceCaps_set_maxComputeSharedMemorySize)); cls->defineProperty("maxComputeWorkGroupInvocations", _SE(js_gfx_DeviceCaps_get_maxComputeWorkGroupInvocations), _SE(js_gfx_DeviceCaps_set_maxComputeWorkGroupInvocations)); @@ -3779,6 +3709,355 @@ bool js_register_gfx_BindingMappingInfo(se::Object* obj) // NOLINT(readability-i se::ScriptEngine::getInstance()->clearException(); return true; } +se::Object* __jsb_cc_gfx_SwapchainInfo_proto = nullptr; +se::Class* __jsb_cc_gfx_SwapchainInfo_class = nullptr; + +static bool js_gfx_SwapchainInfo_get_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_get_windowHandle : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->windowHandle, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->windowHandle, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SwapchainInfo_get_windowHandle) + +static bool js_gfx_SwapchainInfo_set_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_set_windowHandle : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->windowHandle, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SwapchainInfo_set_windowHandle : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SwapchainInfo_set_windowHandle) + +static bool js_gfx_SwapchainInfo_get_vsyncMode(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_get_vsyncMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->vsyncMode, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->vsyncMode, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SwapchainInfo_get_vsyncMode) + +static bool js_gfx_SwapchainInfo_set_vsyncMode(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_set_vsyncMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->vsyncMode, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SwapchainInfo_set_vsyncMode : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SwapchainInfo_set_vsyncMode) + +static bool js_gfx_SwapchainInfo_get_width(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_get_width : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->width, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->width, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SwapchainInfo_get_width) + +static bool js_gfx_SwapchainInfo_set_width(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_set_width : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->width, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SwapchainInfo_set_width : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SwapchainInfo_set_width) + +static bool js_gfx_SwapchainInfo_get_height(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_get_height : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->height, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->height, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SwapchainInfo_get_height) + +static bool js_gfx_SwapchainInfo_set_height(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SwapchainInfo_set_height : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->height, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SwapchainInfo_set_height : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SwapchainInfo_set_height) + + +template<> +bool sevalue_to_native(const se::Value &from, cc::gfx::SwapchainInfo * to, se::Object *ctx) +{ + assert(from.isObject()); + se::Object *json = from.toObject(); + auto* data = reinterpret_cast(json->getPrivateData()); + if (data) { + *to = *data; + return true; + } + se::Value field; + bool ok = true; + json->getProperty("windowHandle", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->windowHandle), ctx); + } + json->getProperty("vsyncMode", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->vsyncMode), ctx); + } + json->getProperty("width", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->width), ctx); + } + json->getProperty("height", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->height), ctx); + } + return ok; +} + +SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_SwapchainInfo_finalize) + +static bool js_gfx_SwapchainInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + if(argc == 0) + { + cc::gfx::SwapchainInfo* cobj = JSB_ALLOC(cc::gfx::SwapchainInfo); + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; + } + + if(argc == 1 && args[0].isObject()) + { + se::Object *json = args[0].toObject(); + se::Value field; + + cc::gfx::SwapchainInfo* cobj = JSB_ALLOC(cc::gfx::SwapchainInfo); + ok &= sevalue_to_native(args[0], cobj, s.thisObject()); + if(!ok) { + JSB_FREE(cobj); + SE_REPORT_ERROR("argument convertion error"); + return false; + } + + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; + } + + cc::gfx::SwapchainInfo* cobj = JSB_ALLOC(cc::gfx::SwapchainInfo); + if (argc > 0 && !args[0].isUndefined()) { + ok &= sevalue_to_native(args[0], &(cobj->windowHandle), nullptr); + } + if (argc > 1 && !args[1].isUndefined()) { + ok &= sevalue_to_native(args[1], &(cobj->vsyncMode), nullptr); + } + if (argc > 2 && !args[2].isUndefined()) { + ok &= sevalue_to_native(args[2], &(cobj->width), nullptr); + } + if (argc > 3 && !args[3].isUndefined()) { + ok &= sevalue_to_native(args[3], &(cobj->height), nullptr); + } + + if(!ok) { + JSB_FREE(cobj); + SE_REPORT_ERROR("Argument convertion error"); + return false; + } + + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; +} +SE_BIND_CTOR(js_gfx_SwapchainInfo_constructor, __jsb_cc_gfx_SwapchainInfo_class, js_cc_gfx_SwapchainInfo_finalize) + + + +static bool js_cc_gfx_SwapchainInfo_finalize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + auto* cobj = SE_THIS_OBJECT(s); + JSB_FREE(cobj); + } + return true; +} +SE_BIND_FINALIZE_FUNC(js_cc_gfx_SwapchainInfo_finalize) + +bool js_register_gfx_SwapchainInfo(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("SwapchainInfo", obj, nullptr, _SE(js_gfx_SwapchainInfo_constructor)); + + cls->defineProperty("windowHandle", _SE(js_gfx_SwapchainInfo_get_windowHandle), _SE(js_gfx_SwapchainInfo_set_windowHandle)); + cls->defineProperty("vsyncMode", _SE(js_gfx_SwapchainInfo_get_vsyncMode), _SE(js_gfx_SwapchainInfo_set_vsyncMode)); + cls->defineProperty("width", _SE(js_gfx_SwapchainInfo_get_width), _SE(js_gfx_SwapchainInfo_set_width)); + cls->defineProperty("height", _SE(js_gfx_SwapchainInfo_get_height), _SE(js_gfx_SwapchainInfo_set_height)); + cls->defineFinalizeFunction(_SE(js_cc_gfx_SwapchainInfo_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_gfx_SwapchainInfo_proto = cls->getProto(); + __jsb_cc_gfx_SwapchainInfo_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + return true; +} +se::Object* __jsb_cc_gfx_DeviceInfo_proto = nullptr; +se::Class* __jsb_cc_gfx_DeviceInfo_class = nullptr; + +static bool js_gfx_DeviceInfo_get_bindingMappingInfo(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_bindingMappingInfo : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->bindingMappingInfo, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->bindingMappingInfo, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_bindingMappingInfo) + +static bool js_gfx_DeviceInfo_set_bindingMappingInfo(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_bindingMappingInfo : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->bindingMappingInfo, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_bindingMappingInfo : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_bindingMappingInfo) + + +template<> +bool sevalue_to_native(const se::Value &from, cc::gfx::DeviceInfo * to, se::Object *ctx) +{ + assert(from.isObject()); + se::Object *json = from.toObject(); + auto* data = reinterpret_cast(json->getPrivateData()); + if (data) { + *to = *data; + return true; + } + se::Value field; + bool ok = true; + json->getProperty("bindingMappingInfo", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->bindingMappingInfo), ctx); + } + return ok; +} + +SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_DeviceInfo_finalize) + +static bool js_gfx_DeviceInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) +{ + CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + + if(argc == 0) + { + cc::gfx::DeviceInfo* cobj = JSB_ALLOC(cc::gfx::DeviceInfo); + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; + } + + cc::gfx::DeviceInfo* cobj = JSB_ALLOC(cc::gfx::DeviceInfo); + if (argc > 0 && !args[0].isUndefined()) { + ok &= sevalue_to_native(args[0], &(cobj->bindingMappingInfo), nullptr); + } + + if(!ok) { + JSB_FREE(cobj); + SE_REPORT_ERROR("Argument convertion error"); + return false; + } + + s.thisObject()->setPrivateData(cobj); + se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); + return true; +} +SE_BIND_CTOR(js_gfx_DeviceInfo_constructor, __jsb_cc_gfx_DeviceInfo_class, js_cc_gfx_DeviceInfo_finalize) + + + +static bool js_cc_gfx_DeviceInfo_finalize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + auto* cobj = SE_THIS_OBJECT(s); + JSB_FREE(cobj); + } + return true; +} +SE_BIND_FINALIZE_FUNC(js_cc_gfx_DeviceInfo_finalize) + +bool js_register_gfx_DeviceInfo(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("DeviceInfo", obj, nullptr, _SE(js_gfx_DeviceInfo_constructor)); + + cls->defineProperty("bindingMappingInfo", _SE(js_gfx_DeviceInfo_get_bindingMappingInfo), _SE(js_gfx_DeviceInfo_set_bindingMappingInfo)); + cls->defineFinalizeFunction(_SE(js_cc_gfx_DeviceInfo_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_gfx_DeviceInfo_proto = cls->getProto(); + __jsb_cc_gfx_DeviceInfo_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + return true; +} se::Object* __jsb_cc_gfx_BufferInfo_proto = nullptr; se::Class* __jsb_cc_gfx_BufferInfo_class = nullptr; @@ -5249,6 +5528,33 @@ static bool js_gfx_TextureInfo_set_depth(se::State& s) // NOLINT(readability-ide } SE_BIND_PROP_SET(js_gfx_TextureInfo_set_depth) +static bool js_gfx_TextureInfo_get_externalRes(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_TextureInfo_get_externalRes : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->externalRes, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->externalRes, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_TextureInfo_get_externalRes) + +static bool js_gfx_TextureInfo_set_externalRes(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_TextureInfo_set_externalRes : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->externalRes, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_TextureInfo_set_externalRes : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_TextureInfo_set_externalRes) + template<> bool sevalue_to_native(const se::Value &from, cc::gfx::TextureInfo * to, se::Object *ctx) @@ -5302,6 +5608,10 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::TextureInfo * to, se::Obj if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->depth), ctx); } + json->getProperty("externalRes", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->externalRes), ctx); + } return ok; } @@ -5370,6 +5680,9 @@ static bool js_gfx_TextureInfo_constructor(se::State& s) // NOLINT(readability-i if (argc > 9 && !args[9].isUndefined()) { ok &= sevalue_to_native(args[9], &(cobj->depth), nullptr); } + if (argc > 10 && !args[10].isUndefined()) { + ok &= sevalue_to_native(args[10], &(cobj->externalRes), nullptr); + } if(!ok) { JSB_FREE(cobj); @@ -5412,6 +5725,7 @@ bool js_register_gfx_TextureInfo(se::Object* obj) // NOLINT(readability-identifi cls->defineProperty("levelCount", _SE(js_gfx_TextureInfo_get_levelCount), _SE(js_gfx_TextureInfo_set_levelCount)); cls->defineProperty("samples", _SE(js_gfx_TextureInfo_get_samples), _SE(js_gfx_TextureInfo_set_samples)); cls->defineProperty("depth", _SE(js_gfx_TextureInfo_get_depth), _SE(js_gfx_TextureInfo_set_depth)); + cls->defineProperty("externalRes", _SE(js_gfx_TextureInfo_get_externalRes), _SE(js_gfx_TextureInfo_set_externalRes)); cls->defineFinalizeFunction(_SE(js_cc_gfx_TextureInfo_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -5982,60 +6296,6 @@ static bool js_gfx_SamplerInfo_set_cmpFunc(se::State& s) // NOLINT(readability-i } SE_BIND_PROP_SET(js_gfx_SamplerInfo_set_cmpFunc) -static bool js_gfx_SamplerInfo_get_borderColor(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_SamplerInfo_get_borderColor : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->borderColor, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->borderColor, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_SamplerInfo_get_borderColor) - -static bool js_gfx_SamplerInfo_set_borderColor(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_SamplerInfo_set_borderColor : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->borderColor, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_SamplerInfo_set_borderColor : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_SamplerInfo_set_borderColor) - -static bool js_gfx_SamplerInfo_get_mipLODBias(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_SamplerInfo_get_mipLODBias : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->mipLODBias, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->mipLODBias, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_SamplerInfo_get_mipLODBias) - -static bool js_gfx_SamplerInfo_set_mipLODBias(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_SamplerInfo_set_mipLODBias : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->mipLODBias, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_SamplerInfo_set_mipLODBias : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_SamplerInfo_set_mipLODBias) - template<> bool sevalue_to_native(const se::Value &from, cc::gfx::SamplerInfo * to, se::Object *ctx) @@ -6081,14 +6341,6 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::SamplerInfo * to, se::Obj if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->cmpFunc), ctx); } - json->getProperty("borderColor", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->borderColor), ctx); - } - json->getProperty("mipLODBias", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->mipLODBias), ctx); - } return ok; } @@ -6151,12 +6403,6 @@ static bool js_gfx_SamplerInfo_constructor(se::State& s) // NOLINT(readability-i if (argc > 7 && !args[7].isUndefined()) { ok &= sevalue_to_native(args[7], &(cobj->cmpFunc), nullptr); } - if (argc > 8 && !args[8].isUndefined()) { - ok &= sevalue_to_native(args[8], &(cobj->borderColor), nullptr); - } - if (argc > 9 && !args[9].isUndefined()) { - ok &= sevalue_to_native(args[9], &(cobj->mipLODBias), nullptr); - } if(!ok) { JSB_FREE(cobj); @@ -6197,8 +6443,6 @@ bool js_register_gfx_SamplerInfo(se::Object* obj) // NOLINT(readability-identifi cls->defineProperty("addressW", _SE(js_gfx_SamplerInfo_get_addressW), _SE(js_gfx_SamplerInfo_set_addressW)); cls->defineProperty("maxAnisotropy", _SE(js_gfx_SamplerInfo_get_maxAnisotropy), _SE(js_gfx_SamplerInfo_set_maxAnisotropy)); cls->defineProperty("cmpFunc", _SE(js_gfx_SamplerInfo_get_cmpFunc), _SE(js_gfx_SamplerInfo_set_cmpFunc)); - cls->defineProperty("borderColor", _SE(js_gfx_SamplerInfo_get_borderColor), _SE(js_gfx_SamplerInfo_set_borderColor)); - cls->defineProperty("mipLODBias", _SE(js_gfx_SamplerInfo_get_mipLODBias), _SE(js_gfx_SamplerInfo_set_mipLODBias)); cls->defineFinalizeFunction(_SE(js_cc_gfx_SamplerInfo_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -15202,583 +15446,6 @@ bool js_register_gfx_MemoryStatus(se::Object* obj) // NOLINT(readability-identif se::ScriptEngine::getInstance()->clearException(); return true; } -se::Object* __jsb_cc_gfx_DeviceInfo_proto = nullptr; -se::Class* __jsb_cc_gfx_DeviceInfo_class = nullptr; - -static bool js_gfx_DeviceInfo_get_isAntiAlias(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_isAntiAlias : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->isAntiAlias, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->isAntiAlias, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_isAntiAlias) - -static bool js_gfx_DeviceInfo_set_isAntiAlias(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_isAntiAlias : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->isAntiAlias, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_isAntiAlias : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_isAntiAlias) - -static bool js_gfx_DeviceInfo_get_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_windowHandle : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->windowHandle, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->windowHandle, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_windowHandle) - -static bool js_gfx_DeviceInfo_set_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_windowHandle : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->windowHandle, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_windowHandle : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_windowHandle) - -static bool js_gfx_DeviceInfo_get_width(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_width : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->width, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->width, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_width) - -static bool js_gfx_DeviceInfo_set_width(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_width : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->width, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_width : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_width) - -static bool js_gfx_DeviceInfo_get_height(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_height : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->height, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->height, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_height) - -static bool js_gfx_DeviceInfo_set_height(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_height : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->height, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_height : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_height) - -static bool js_gfx_DeviceInfo_get_pixelRatio(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_pixelRatio : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->pixelRatio, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->pixelRatio, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_pixelRatio) - -static bool js_gfx_DeviceInfo_set_pixelRatio(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_pixelRatio : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->pixelRatio, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_pixelRatio : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_pixelRatio) - -static bool js_gfx_DeviceInfo_get_bindingMappingInfo(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_get_bindingMappingInfo : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->bindingMappingInfo, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->bindingMappingInfo, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_DeviceInfo_get_bindingMappingInfo) - -static bool js_gfx_DeviceInfo_set_bindingMappingInfo(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_DeviceInfo_set_bindingMappingInfo : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->bindingMappingInfo, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_DeviceInfo_set_bindingMappingInfo : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_DeviceInfo_set_bindingMappingInfo) - - -template<> -bool sevalue_to_native(const se::Value &from, cc::gfx::DeviceInfo * to, se::Object *ctx) -{ - assert(from.isObject()); - se::Object *json = from.toObject(); - auto* data = reinterpret_cast(json->getPrivateData()); - if (data) { - *to = *data; - return true; - } - se::Value field; - bool ok = true; - json->getProperty("isAntiAlias", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->isAntiAlias), ctx); - } - json->getProperty("windowHandle", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->windowHandle), ctx); - } - json->getProperty("width", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->width), ctx); - } - json->getProperty("height", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->height), ctx); - } - json->getProperty("pixelRatio", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->pixelRatio), ctx); - } - json->getProperty("bindingMappingInfo", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->bindingMappingInfo), ctx); - } - return ok; -} - -SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_DeviceInfo_finalize) - -static bool js_gfx_DeviceInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - if(argc == 0) - { - cc::gfx::DeviceInfo* cobj = JSB_ALLOC(cc::gfx::DeviceInfo); - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; - } - - if(argc == 1 && args[0].isObject()) - { - se::Object *json = args[0].toObject(); - se::Value field; - - cc::gfx::DeviceInfo* cobj = JSB_ALLOC(cc::gfx::DeviceInfo); - ok &= sevalue_to_native(args[0], cobj, s.thisObject()); - if(!ok) { - JSB_FREE(cobj); - SE_REPORT_ERROR("argument convertion error"); - return false; - } - - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; - } - - cc::gfx::DeviceInfo* cobj = JSB_ALLOC(cc::gfx::DeviceInfo); - if (argc > 0 && !args[0].isUndefined()) { - ok &= sevalue_to_native(args[0], &(cobj->isAntiAlias), nullptr); - } - if (argc > 1 && !args[1].isUndefined()) { - ok &= sevalue_to_native(args[1], &(cobj->windowHandle), nullptr); - } - if (argc > 2 && !args[2].isUndefined()) { - ok &= sevalue_to_native(args[2], &(cobj->width), nullptr); - } - if (argc > 3 && !args[3].isUndefined()) { - ok &= sevalue_to_native(args[3], &(cobj->height), nullptr); - } - if (argc > 4 && !args[4].isUndefined()) { - ok &= sevalue_to_native(args[4], &(cobj->pixelRatio), nullptr); - } - if (argc > 5 && !args[5].isUndefined()) { - ok &= sevalue_to_native(args[5], &(cobj->bindingMappingInfo), nullptr); - } - - if(!ok) { - JSB_FREE(cobj); - SE_REPORT_ERROR("Argument convertion error"); - return false; - } - - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; -} -SE_BIND_CTOR(js_gfx_DeviceInfo_constructor, __jsb_cc_gfx_DeviceInfo_class, js_cc_gfx_DeviceInfo_finalize) - - - -static bool js_cc_gfx_DeviceInfo_finalize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); - JSB_FREE(cobj); - } - return true; -} -SE_BIND_FINALIZE_FUNC(js_cc_gfx_DeviceInfo_finalize) - -bool js_register_gfx_DeviceInfo(se::Object* obj) // NOLINT(readability-identifier-naming) -{ - auto* cls = se::Class::create("DeviceInfo", obj, nullptr, _SE(js_gfx_DeviceInfo_constructor)); - - cls->defineProperty("isAntiAlias", _SE(js_gfx_DeviceInfo_get_isAntiAlias), _SE(js_gfx_DeviceInfo_set_isAntiAlias)); - cls->defineProperty("windowHandle", _SE(js_gfx_DeviceInfo_get_windowHandle), _SE(js_gfx_DeviceInfo_set_windowHandle)); - cls->defineProperty("width", _SE(js_gfx_DeviceInfo_get_width), _SE(js_gfx_DeviceInfo_set_width)); - cls->defineProperty("height", _SE(js_gfx_DeviceInfo_get_height), _SE(js_gfx_DeviceInfo_set_height)); - cls->defineProperty("pixelRatio", _SE(js_gfx_DeviceInfo_get_pixelRatio), _SE(js_gfx_DeviceInfo_set_pixelRatio)); - cls->defineProperty("bindingMappingInfo", _SE(js_gfx_DeviceInfo_get_bindingMappingInfo), _SE(js_gfx_DeviceInfo_set_bindingMappingInfo)); - cls->defineFinalizeFunction(_SE(js_cc_gfx_DeviceInfo_finalize)); - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_gfx_DeviceInfo_proto = cls->getProto(); - __jsb_cc_gfx_DeviceInfo_class = cls; - - se::ScriptEngine::getInstance()->clearException(); - return true; -} -se::Object* __jsb_cc_gfx_ContextInfo_proto = nullptr; -se::Class* __jsb_cc_gfx_ContextInfo_class = nullptr; - -static bool js_gfx_ContextInfo_get_msaaEnabled(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_get_msaaEnabled : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->msaaEnabled, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->msaaEnabled, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_ContextInfo_get_msaaEnabled) - -static bool js_gfx_ContextInfo_set_msaaEnabled(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_set_msaaEnabled : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->msaaEnabled, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_ContextInfo_set_msaaEnabled : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_ContextInfo_set_msaaEnabled) - -static bool js_gfx_ContextInfo_get_performance(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_get_performance : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->performance, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->performance, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_ContextInfo_get_performance) - -static bool js_gfx_ContextInfo_set_performance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_set_performance : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->performance, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_ContextInfo_set_performance : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_ContextInfo_set_performance) - -static bool js_gfx_ContextInfo_get_vsyncMode(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_get_vsyncMode : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->vsyncMode, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->vsyncMode, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_ContextInfo_get_vsyncMode) - -static bool js_gfx_ContextInfo_set_vsyncMode(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_set_vsyncMode : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->vsyncMode, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_ContextInfo_set_vsyncMode : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_ContextInfo_set_vsyncMode) - -static bool js_gfx_ContextInfo_get_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_get_windowHandle : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->windowHandle, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->windowHandle, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_ContextInfo_get_windowHandle) - -static bool js_gfx_ContextInfo_set_windowHandle(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_set_windowHandle : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->windowHandle, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_ContextInfo_set_windowHandle : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_ContextInfo_set_windowHandle) - -static bool js_gfx_ContextInfo_get_sharedCtx(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_get_sharedCtx : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->sharedCtx, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->sharedCtx, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_ContextInfo_get_sharedCtx) - -static bool js_gfx_ContextInfo_set_sharedCtx(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_ContextInfo_set_sharedCtx : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->sharedCtx, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_ContextInfo_set_sharedCtx : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_ContextInfo_set_sharedCtx) - - -template<> -bool sevalue_to_native(const se::Value &from, cc::gfx::ContextInfo * to, se::Object *ctx) -{ - assert(from.isObject()); - se::Object *json = from.toObject(); - auto* data = reinterpret_cast(json->getPrivateData()); - if (data) { - *to = *data; - return true; - } - se::Value field; - bool ok = true; - json->getProperty("msaaEnabled", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->msaaEnabled), ctx); - } - json->getProperty("performance", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->performance), ctx); - } - json->getProperty("vsyncMode", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->vsyncMode), ctx); - } - json->getProperty("windowHandle", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->windowHandle), ctx); - } - json->getProperty("sharedCtx", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->sharedCtx), ctx); - } - return ok; -} - -SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_ContextInfo_finalize) - -static bool js_gfx_ContextInfo_constructor(se::State& s) // NOLINT(readability-identifier-naming) -{ - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - if(argc == 0) - { - cc::gfx::ContextInfo* cobj = JSB_ALLOC(cc::gfx::ContextInfo); - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; - } - - if(argc == 1 && args[0].isObject()) - { - se::Object *json = args[0].toObject(); - se::Value field; - - cc::gfx::ContextInfo* cobj = JSB_ALLOC(cc::gfx::ContextInfo); - ok &= sevalue_to_native(args[0], cobj, s.thisObject()); - if(!ok) { - JSB_FREE(cobj); - SE_REPORT_ERROR("argument convertion error"); - return false; - } - - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; - } - - cc::gfx::ContextInfo* cobj = JSB_ALLOC(cc::gfx::ContextInfo); - if (argc > 0 && !args[0].isUndefined()) { - ok &= sevalue_to_native(args[0], &(cobj->msaaEnabled), nullptr); - } - if (argc > 1 && !args[1].isUndefined()) { - ok &= sevalue_to_native(args[1], &(cobj->performance), nullptr); - } - if (argc > 2 && !args[2].isUndefined()) { - ok &= sevalue_to_native(args[2], &(cobj->vsyncMode), nullptr); - } - if (argc > 3 && !args[3].isUndefined()) { - ok &= sevalue_to_native(args[3], &(cobj->windowHandle), nullptr); - } - if (argc > 4 && !args[4].isUndefined()) { - ok &= sevalue_to_native(args[4], &(cobj->sharedCtx), nullptr); - } - - if(!ok) { - JSB_FREE(cobj); - SE_REPORT_ERROR("Argument convertion error"); - return false; - } - - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; -} -SE_BIND_CTOR(js_gfx_ContextInfo_constructor, __jsb_cc_gfx_ContextInfo_class, js_cc_gfx_ContextInfo_finalize) - - - -static bool js_cc_gfx_ContextInfo_finalize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); - JSB_FREE(cobj); - } - return true; -} -SE_BIND_FINALIZE_FUNC(js_cc_gfx_ContextInfo_finalize) - -bool js_register_gfx_ContextInfo(se::Object* obj) // NOLINT(readability-identifier-naming) -{ - auto* cls = se::Class::create("ContextInfo", obj, nullptr, _SE(js_gfx_ContextInfo_constructor)); - - cls->defineProperty("msaaEnabled", _SE(js_gfx_ContextInfo_get_msaaEnabled), _SE(js_gfx_ContextInfo_set_msaaEnabled)); - cls->defineProperty("performance", _SE(js_gfx_ContextInfo_get_performance), _SE(js_gfx_ContextInfo_set_performance)); - cls->defineProperty("vsyncMode", _SE(js_gfx_ContextInfo_get_vsyncMode), _SE(js_gfx_ContextInfo_set_vsyncMode)); - cls->defineProperty("windowHandle", _SE(js_gfx_ContextInfo_get_windowHandle), _SE(js_gfx_ContextInfo_set_windowHandle)); - cls->defineProperty("sharedCtx", _SE(js_gfx_ContextInfo_get_sharedCtx), _SE(js_gfx_ContextInfo_set_sharedCtx)); - cls->defineFinalizeFunction(_SE(js_cc_gfx_ContextInfo_finalize)); - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_gfx_ContextInfo_proto = cls->getProto(); - __jsb_cc_gfx_ContextInfo_class = cls; - - se::ScriptEngine::getInstance()->clearException(); - return true; -} se::Object* __jsb_cc_gfx_GFXObject_proto = nullptr; se::Class* __jsb_cc_gfx_GFXObject_class = nullptr; @@ -15839,21 +15506,6 @@ static bool js_gfx_GFXObject_getTypedID(se::State& s) // NOLINT(readability-iden } SE_BIND_PROP_GET(js_gfx_GFXObject_getTypedID) -static bool js_gfx_GFXObject_resizeObjectID(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_GFXObject_resizeObjectID : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->resizeObjectID(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_GFXObject_resizeObjectID) - SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_GFXObject_finalize) static bool js_gfx_GFXObject_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c @@ -15889,10 +15541,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->defineFunction("resizeObjectID", _SE(js_gfx_GFXObject_resizeObjectID)); + 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); @@ -16122,12 +15773,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("isBufferView", _SE(js_gfx_Buffer_isBufferView)); cls->defineFunction("resize", _SE(js_gfx_Buffer_resize)); @@ -16198,62 +15849,24 @@ static bool js_gfx_InputAssembler_getAttributesHash(se::State& s) // NOLINT(read } SE_BIND_PROP_GET(js_gfx_InputAssembler_getAttributesHash) -static bool js_gfx_InputAssembler_getFirstIndex(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_InputAssembler_getDrawInfo(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getFirstIndex : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getDrawInfo : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - unsigned int result = cobj->getFirstIndex(); + const cc::gfx::DrawInfo& result = cobj->getDrawInfo(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getFirstIndex : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getDrawInfo : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_PROP_GET(js_gfx_InputAssembler_getFirstIndex) - -static bool js_gfx_InputAssembler_getFirstInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getFirstInstance : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getFirstInstance(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getFirstInstance : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getFirstInstance) - -static bool js_gfx_InputAssembler_getFirstVertex(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getFirstVertex : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getFirstVertex(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getFirstVertex : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getFirstVertex) +SE_BIND_PROP_GET(js_gfx_InputAssembler_getDrawInfo) static bool js_gfx_InputAssembler_getIndexBuffer(se::State& s) // NOLINT(readability-identifier-naming) { @@ -16274,25 +15887,6 @@ static bool js_gfx_InputAssembler_getIndexBuffer(se::State& s) // NOLINT(readabi } SE_BIND_PROP_GET(js_gfx_InputAssembler_getIndexBuffer) -static bool js_gfx_InputAssembler_getIndexCount(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getIndexCount : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getIndexCount(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getIndexCount : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getIndexCount) - static bool js_gfx_InputAssembler_getIndirectBuffer(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -16312,25 +15906,6 @@ static bool js_gfx_InputAssembler_getIndirectBuffer(se::State& s) // NOLINT(read } SE_BIND_PROP_GET(js_gfx_InputAssembler_getIndirectBuffer) -static bool js_gfx_InputAssembler_getInstanceCount(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getInstanceCount : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getInstanceCount(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getInstanceCount : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getInstanceCount) - static bool js_gfx_InputAssembler_getVertexBuffers(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -16350,44 +15925,6 @@ static bool js_gfx_InputAssembler_getVertexBuffers(se::State& s) // NOLINT(reada } SE_BIND_PROP_GET(js_gfx_InputAssembler_getVertexBuffers) -static bool js_gfx_InputAssembler_getVertexCount(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getVertexCount : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getVertexCount(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getVertexCount : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getVertexCount) - -static bool js_gfx_InputAssembler_getVertexOffset(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_getVertexOffset : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getVertexOffset(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_getVertexOffset : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_InputAssembler_getVertexOffset) - static bool js_gfx_InputAssembler_initialize(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -16529,7 +16066,7 @@ static bool js_gfx_InputAssembler_setVertexOffset(se::State& s) // NOLINT(readab size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); SE_PRECONDITION2(ok, false, "js_gfx_InputAssembler_setVertexOffset : Error processing arguments"); cobj->setVertexOffset(arg0.value()); @@ -16569,18 +16106,19 @@ 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("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("indexBuffer", _SE(js_gfx_InputAssembler_getIndexBuffer), nullptr); cls->defineProperty("indirectBuffer", _SE(js_gfx_InputAssembler_getIndirectBuffer), nullptr); - cls->defineProperty("firstVertex", _SE(js_gfx_InputAssembler_getFirstVertex), _SE(js_gfx_InputAssembler_setFirstVertex)); + cls->defineProperty("attributesHash", _SE(js_gfx_InputAssembler_getAttributesHash), nullptr); + cls->defineProperty("drawInfo", _SE(js_gfx_InputAssembler_getDrawInfo), nullptr); + cls->defineProperty("vertexCount", nullptr, _SE(js_gfx_InputAssembler_setVertexCount)); + cls->defineProperty("firstVertex", nullptr, _SE(js_gfx_InputAssembler_setFirstVertex)); + cls->defineProperty("indexCount", nullptr, _SE(js_gfx_InputAssembler_setIndexCount)); + cls->defineProperty("firstIndex", nullptr, _SE(js_gfx_InputAssembler_setFirstIndex)); + cls->defineProperty("vertexOffset", nullptr, _SE(js_gfx_InputAssembler_setVertexOffset)); + cls->defineProperty("instanceCount", nullptr, _SE(js_gfx_InputAssembler_setInstanceCount)); + cls->defineProperty("firstInstance", nullptr, _SE(js_gfx_InputAssembler_setFirstInstance)); cls->defineFunction("destroy", _SE(js_gfx_InputAssembler_destroy)); cls->defineFunction("initialize", _SE(js_gfx_InputAssembler_initialize)); cls->defineFinalizeFunction(_SE(js_cc_gfx_InputAssembler_finalize)); @@ -16658,39 +16196,13 @@ static bool js_gfx_CommandBuffer_begin(se::State& s) // NOLINT(readability-ident } SE_BIND_FUNC(js_gfx_CommandBuffer_begin) -static bool js_gfx_CommandBuffer_beginRenderPassForJS(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_CommandBuffer_beginRenderPass(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2( cobj, false, "js_gfx_CommandBuffer_beginRenderPassForJS : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_gfx_CommandBuffer_beginRenderPass : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - do { - if (argc == 6) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - HolderType, true> arg3 = {}; - HolderType arg4 = {}; - HolderType arg5 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->beginRenderPassForJS(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value()); - return true; - } - } while(false); - do { if (argc == 7) { HolderType arg0 = {}; @@ -16715,7 +16227,91 @@ static bool js_gfx_CommandBuffer_beginRenderPassForJS(se::State& s) // NOLINT(re if (!ok) { ok = true; break; } ok &= sevalue_to_native(args[6], &arg6, s.thisObject()); if (!ok) { ok = true; break; } - cobj->beginRenderPassForJS(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value(), arg6.value()); + cobj->beginRenderPass(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value(), arg6.value()); + return true; + } + } while(false); + + do { + if (argc == 8) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + HolderType arg4 = {}; + HolderType arg5 = {}; + HolderType arg6 = {}; + HolderType arg7 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[6], &arg6, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[7], &arg7, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->beginRenderPass(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value(), arg6.value(), arg7.value()); + return true; + } + } while(false); + + do { + if (argc == 6) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType, true> arg3 = {}; + HolderType arg4 = {}; + HolderType arg5 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->beginRenderPass(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value()); + return true; + } + } while(false); + + do { + if (argc == 6) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + HolderType arg4 = {}; + HolderType arg5 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[4], &arg4, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[5], &arg5, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->beginRenderPass(arg0.value(), arg1.value(), arg2.value(), arg3.value(), arg4.value(), arg5.value()); return true; } } while(false); @@ -16723,15 +16319,49 @@ static bool js_gfx_CommandBuffer_beginRenderPassForJS(se::State& s) // NOLINT(re SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } -SE_BIND_FUNC(js_gfx_CommandBuffer_beginRenderPassForJS) +SE_BIND_FUNC(js_gfx_CommandBuffer_beginRenderPass) -static bool js_gfx_CommandBuffer_bindDescriptorSetForJS(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_CommandBuffer_bindDescriptorSet(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2( cobj, false, "js_gfx_CommandBuffer_bindDescriptorSetForJS : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_gfx_CommandBuffer_bindDescriptorSet : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); + do { + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->bindDescriptorSet(arg0.value(), arg1.value()); + return true; + } + } while(false); + + do { + if (argc == 4) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + HolderType arg3 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->bindDescriptorSet(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + return true; + } + } while(false); + do { if (argc == 3) { HolderType arg0 = {}; @@ -16744,21 +16374,7 @@ static bool js_gfx_CommandBuffer_bindDescriptorSetForJS(se::State& s) // NOLINT( if (!ok) { ok = true; break; } ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); if (!ok) { ok = true; break; } - cobj->bindDescriptorSetForJS(arg0.value(), arg1.value(), arg2.value()); - return true; - } - } while(false); - - do { - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - if (!ok) { ok = true; break; } - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - if (!ok) { ok = true; break; } - cobj->bindDescriptorSetForJS(arg0.value(), arg1.value()); + cobj->bindDescriptorSet(arg0.value(), arg1.value(), arg2.value()); return true; } } while(false); @@ -16766,7 +16382,7 @@ static bool js_gfx_CommandBuffer_bindDescriptorSetForJS(se::State& s) // NOLINT( SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } -SE_BIND_FUNC(js_gfx_CommandBuffer_bindDescriptorSetForJS) +SE_BIND_FUNC(js_gfx_CommandBuffer_bindDescriptorSet) static bool js_gfx_CommandBuffer_bindInputAssembler(se::State& s) // NOLINT(readability-identifier-naming) { @@ -16837,7 +16453,7 @@ static bool js_gfx_CommandBuffer_blitTexture(se::State& s) // NOLINT(readability if (argc == 5) { HolderType arg0 = {}; HolderType arg1 = {}; - HolderType arg2 = {}; + HolderType arg2 = {}; HolderType arg3 = {}; HolderType arg4 = {}; @@ -17097,7 +16713,7 @@ static bool js_gfx_CommandBuffer_pipelineBarrier(se::State& s) // NOLINT(readabi size_t argc = args.size(); do { if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -17108,9 +16724,9 @@ static bool js_gfx_CommandBuffer_pipelineBarrier(se::State& s) // NOLINT(readabi do { if (argc == 4) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; HolderType arg3 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -17128,7 +16744,7 @@ static bool js_gfx_CommandBuffer_pipelineBarrier(se::State& s) // NOLINT(readabi do { if (argc == 3) { - HolderType arg0 = {}; + HolderType arg0 = {}; HolderType, true> arg1 = {}; HolderType, true> arg2 = {}; @@ -17342,8 +16958,8 @@ bool js_register_gfx_CommandBuffer(se::Object* obj) // NOLINT(readability-identi auto* cls = se::Class::create("CommandBuffer", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_CommandBuffer_constructor)); cls->defineFunction("begin", _SE(js_gfx_CommandBuffer_begin)); - cls->defineFunction("beginRenderPass", _SE(js_gfx_CommandBuffer_beginRenderPassForJS)); - cls->defineFunction("bindDescriptorSet", _SE(js_gfx_CommandBuffer_bindDescriptorSetForJS)); + cls->defineFunction("beginRenderPass", _SE(js_gfx_CommandBuffer_beginRenderPass)); + cls->defineFunction("bindDescriptorSet", _SE(js_gfx_CommandBuffer_bindDescriptorSet)); cls->defineFunction("bindInputAssembler", _SE(js_gfx_CommandBuffer_bindInputAssembler)); cls->defineFunction("bindPipelineState", _SE(js_gfx_CommandBuffer_bindPipelineState)); cls->defineFunction("blitTexture", _SE(js_gfx_CommandBuffer_blitTexture)); @@ -17378,183 +16994,6 @@ bool js_register_gfx_CommandBuffer(se::Object* obj) // NOLINT(readability-identi se::ScriptEngine::getInstance()->clearException(); return true; } -se::Object* __jsb_cc_gfx_Context_proto = nullptr; -se::Class* __jsb_cc_gfx_Context_class = nullptr; - -static bool js_gfx_Context_destroy(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_destroy : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->destroy(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_Context_destroy) - -static bool js_gfx_Context_getColorFormat(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_getColorFormat : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getColorFormat()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Context_getColorFormat : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Context_getColorFormat) - -static bool js_gfx_Context_getDepthStencilFormat(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_getDepthStencilFormat : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getDepthStencilFormat()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Context_getDepthStencilFormat : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Context_getDepthStencilFormat) - -static bool js_gfx_Context_getSharedContext(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_getSharedContext : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::gfx::Context* result = cobj->getSharedContext(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Context_getSharedContext : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Context_getSharedContext) - -static bool js_gfx_Context_getVsyncMode(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_getVsyncMode : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getVsyncMode()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Context_getVsyncMode : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Context_getVsyncMode) - -static bool js_gfx_Context_initialize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_initialize : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Context_initialize : Error processing arguments"); - bool result = cobj->initialize(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Context_initialize : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_Context_initialize) - -static bool js_gfx_Context_present(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Context_present : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->present(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_Context_present) - -SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_Context_finalize) - -static bool js_gfx_Context_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c -{ - //#3 cc::gfx::Context: is_skip_construtor True - se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::Context constructor is skipped\")"); - return false; -} -SE_BIND_CTOR(js_gfx_Context_constructor, __jsb_cc_gfx_Context_class, js_cc_gfx_Context_finalize) - - - -static bool js_cc_gfx_Context_finalize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); - JSB_FREE(cobj); - } - return true; -} -SE_BIND_FINALIZE_FUNC(js_cc_gfx_Context_finalize) - -bool js_register_gfx_Context(se::Object* obj) // NOLINT(readability-identifier-naming) -{ - auto* cls = se::Class::create("Context", obj, nullptr, _SE(js_gfx_Context_constructor)); - - cls->defineProperty("sharedContext", _SE(js_gfx_Context_getSharedContext), nullptr); - cls->defineProperty("vsyncMode", _SE(js_gfx_Context_getVsyncMode), nullptr); - cls->defineProperty("colorFormat", _SE(js_gfx_Context_getColorFormat), nullptr); - cls->defineProperty("depthStencilFormat", _SE(js_gfx_Context_getDepthStencilFormat), nullptr); - cls->defineFunction("destroy", _SE(js_gfx_Context_destroy)); - cls->defineFunction("initialize", _SE(js_gfx_Context_initialize)); - cls->defineFunction("present", _SE(js_gfx_Context_present)); - cls->defineFinalizeFunction(_SE(js_cc_gfx_Context_finalize)); - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_gfx_Context_proto = cls->getProto(); - __jsb_cc_gfx_Context_class = cls; - - se::ScriptEngine::getInstance()->clearException(); - return true; -} se::Object* __jsb_cc_gfx_DescriptorSet_proto = nullptr; se::Class* __jsb_cc_gfx_DescriptorSet_class = nullptr; @@ -18295,8 +17734,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)); @@ -18311,90 +17750,6 @@ bool js_register_gfx_Framebuffer(se::Object* obj) // NOLINT(readability-identifi se::ScriptEngine::getInstance()->clearException(); return true; } -se::Object* __jsb_cc_gfx_GlobalBarrier_proto = nullptr; -se::Class* __jsb_cc_gfx_GlobalBarrier_class = nullptr; - -static bool js_gfx_GlobalBarrier_info(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_GlobalBarrier_info : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - const cc::gfx::GlobalBarrierInfo& result = cobj->info(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_info : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_GlobalBarrier_info) - -static bool js_gfx_GlobalBarrier_computeHash(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_computeHash : Error processing arguments"); - unsigned int result = cc::gfx::GlobalBarrier::computeHash(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_computeHash : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_GlobalBarrier_computeHash) - -SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_GlobalBarrier_finalize) - -static bool js_gfx_GlobalBarrier_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c -{ - cc::gfx::GlobalBarrier* cobj = JSB_ALLOC(cc::gfx::GlobalBarrier); - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; -} -SE_BIND_CTOR(js_gfx_GlobalBarrier_constructor, __jsb_cc_gfx_GlobalBarrier_class, js_cc_gfx_GlobalBarrier_finalize) - - - -static bool js_cc_gfx_GlobalBarrier_finalize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); - JSB_FREE(cobj); - } - return true; -} -SE_BIND_FINALIZE_FUNC(js_cc_gfx_GlobalBarrier_finalize) - -bool js_register_gfx_GlobalBarrier(se::Object* obj) // NOLINT(readability-identifier-naming) -{ - auto* cls = se::Class::create("GlobalBarrier", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_GlobalBarrier_constructor)); - - cls->defineFunction("info", _SE(js_gfx_GlobalBarrier_info)); - cls->defineStaticFunction("computeHash", _SE(js_gfx_GlobalBarrier_computeHash)); - cls->defineFinalizeFunction(_SE(js_cc_gfx_GlobalBarrier_finalize)); - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_gfx_GlobalBarrier_proto = cls->getProto(); - __jsb_cc_gfx_GlobalBarrier_class = cls; - - se::ScriptEngine::getInstance()->clearException(); - return true; -} se::Object* __jsb_cc_gfx_PipelineLayout_proto = nullptr; se::Class* __jsb_cc_gfx_PipelineLayout_class = nullptr; @@ -18749,14 +18104,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)); @@ -18827,24 +18182,42 @@ static bool js_gfx_Queue_initialize(se::State& s) // NOLINT(readability-identifi } SE_BIND_FUNC(js_gfx_Queue_initialize) -static bool js_gfx_Queue_submitForJS(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Queue_submit(se::State& s) // NOLINT(readability-identifier-naming) { + CC_UNUSED bool ok = true; auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Queue_submitForJS : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_gfx_Queue_submit : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType, true> arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Queue_submitForJS : Error processing arguments"); - cobj->submitForJS(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + do { + if (argc == 1) { + HolderType, true> arg0 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->submit(arg0.value()); + return true; + } + } while(false); + + do { + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->submit(arg0.value(), arg1.value()); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } -SE_BIND_FUNC(js_gfx_Queue_submitForJS) +SE_BIND_FUNC(js_gfx_Queue_submit) SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_Queue_finalize) @@ -18878,7 +18251,7 @@ bool js_register_gfx_Queue(se::Object* obj) // NOLINT(readability-identifier-nam cls->defineProperty("type", _SE(js_gfx_Queue_getType), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Queue_destroy)); cls->defineFunction("initialize", _SE(js_gfx_Queue_initialize)); - cls->defineFunction("submit", _SE(js_gfx_Queue_submitForJS)); + cls->defineFunction("submit", _SE(js_gfx_Queue_submit)); cls->defineFinalizeFunction(_SE(js_cc_gfx_Queue_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -19068,284 +18441,6 @@ bool js_register_gfx_RenderPass(se::Object* obj) // NOLINT(readability-identifie se::ScriptEngine::getInstance()->clearException(); return true; } -se::Object* __jsb_cc_gfx_Sampler_proto = nullptr; -se::Class* __jsb_cc_gfx_Sampler_class = nullptr; - -static bool js_gfx_Sampler_destroy(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_destroy : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->destroy(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_Sampler_destroy) - -static bool js_gfx_Sampler_getAddressU(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getAddressU : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getAddressU()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getAddressU : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getAddressU) - -static bool js_gfx_Sampler_getAddressV(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getAddressV : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getAddressV()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getAddressV : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getAddressV) - -static bool js_gfx_Sampler_getAddressW(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getAddressW : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getAddressW()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getAddressW : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getAddressW) - -static bool js_gfx_Sampler_getBorderColor(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getBorderColor : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - const cc::gfx::Color& result = cobj->getBorderColor(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getBorderColor : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getBorderColor) - -static bool js_gfx_Sampler_getCmpFunc(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getCmpFunc : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getCmpFunc()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getCmpFunc : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getCmpFunc) - -static bool js_gfx_Sampler_getMagFilter(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getMagFilter : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getMagFilter()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getMagFilter : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getMagFilter) - -static bool js_gfx_Sampler_getMaxAnisotropy(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getMaxAnisotropy : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getMaxAnisotropy(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getMaxAnisotropy : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getMaxAnisotropy) - -static bool js_gfx_Sampler_getMinFilter(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getMinFilter : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getMinFilter()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getMinFilter : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getMinFilter) - -static bool js_gfx_Sampler_getMipFilter(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getMipFilter : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getMipFilter()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getMipFilter : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getMipFilter) - -static bool js_gfx_Sampler_getMipLODBias(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getMipLODBias : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - float result = cobj->getMipLODBias(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getMipLODBias : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Sampler_getMipLODBias) - -static bool js_gfx_Sampler_initialize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_initialize : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Sampler_initialize : Error processing arguments"); - cobj->initialize(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_Sampler_initialize) - -SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_Sampler_finalize) - -static bool js_gfx_Sampler_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c -{ - //#3 cc::gfx::Sampler: is_skip_construtor True - se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::Sampler constructor is skipped\")"); - return false; -} -SE_BIND_CTOR(js_gfx_Sampler_constructor, __jsb_cc_gfx_Sampler_class, js_cc_gfx_Sampler_finalize) - - - -static bool js_cc_gfx_Sampler_finalize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); - if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) - { - se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); - JSB_FREE(cobj); - } - return true; -} -SE_BIND_FINALIZE_FUNC(js_cc_gfx_Sampler_finalize) - -bool js_register_gfx_Sampler(se::Object* obj) // NOLINT(readability-identifier-naming) -{ - 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("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("mipLODBias", _SE(js_gfx_Sampler_getMipLODBias), nullptr); - cls->defineFunction("destroy", _SE(js_gfx_Sampler_destroy)); - cls->defineFunction("initialize", _SE(js_gfx_Sampler_initialize)); - cls->defineFinalizeFunction(_SE(js_cc_gfx_Sampler_finalize)); - cls->install(); - JSBClassType::registerClass(cls); - - __jsb_cc_gfx_Sampler_proto = cls->getProto(); - __jsb_cc_gfx_Sampler_class = cls; - - se::ScriptEngine::getInstance()->clearException(); - return true; -} se::Object* __jsb_cc_gfx_Shader_proto = nullptr; se::Class* __jsb_cc_gfx_Shader_class = nullptr; @@ -19602,10 +18697,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)); @@ -19642,44 +18737,6 @@ static bool js_gfx_Texture_destroy(se::State& s) // NOLINT(readability-identifie } SE_BIND_FUNC(js_gfx_Texture_destroy) -static bool js_gfx_Texture_getDepth(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getDepth : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getDepth(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getDepth : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Texture_getDepth) - -static bool js_gfx_Texture_getFlags(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getFlags : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getFlags()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getFlags : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Texture_getFlags) - static bool js_gfx_Texture_getFormat(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -19699,6 +18756,25 @@ static bool js_gfx_Texture_getFormat(se::State& s) // NOLINT(readability-identif } SE_BIND_PROP_GET(js_gfx_Texture_getFormat) +static bool js_gfx_Texture_getHash(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getHash : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getHash(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Texture_getHash : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Texture_getHash) + static bool js_gfx_Texture_getHeight(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -19718,62 +18794,24 @@ static bool js_gfx_Texture_getHeight(se::State& s) // NOLINT(readability-identif } SE_BIND_PROP_GET(js_gfx_Texture_getHeight) -static bool js_gfx_Texture_getLayerCount(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Texture_getInfo(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getLayerCount : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getInfo : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - unsigned int result = cobj->getLayerCount(); + const cc::gfx::TextureInfo& result = cobj->getInfo(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getLayerCount : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_Texture_getInfo : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_PROP_GET(js_gfx_Texture_getLayerCount) - -static bool js_gfx_Texture_getLevelCount(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getLevelCount : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getLevelCount(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getLevelCount : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Texture_getLevelCount) - -static bool js_gfx_Texture_getSamples(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getSamples : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getSamples()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getSamples : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Texture_getSamples) +SE_BIND_PROP_GET(js_gfx_Texture_getInfo) static bool js_gfx_Texture_getSize(se::State& s) // NOLINT(readability-identifier-naming) { @@ -19794,43 +18832,24 @@ static bool js_gfx_Texture_getSize(se::State& s) // NOLINT(readability-identifie } SE_BIND_PROP_GET(js_gfx_Texture_getSize) -static bool js_gfx_Texture_getType(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Texture_getViewInfo(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getType : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getViewInfo : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - auto result = static_cast(cobj->getType()); + const cc::gfx::TextureViewInfo& result = cobj->getViewInfo(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getType : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_Texture_getViewInfo : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_PROP_GET(js_gfx_Texture_getType) - -static bool js_gfx_Texture_getUsage(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Texture_getUsage : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getUsage()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_getUsage : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Texture_getUsage) +SE_BIND_PROP_GET(js_gfx_Texture_getViewInfo) static bool js_gfx_Texture_getWidth(se::State& s) // NOLINT(readability-identifier-naming) { @@ -19893,20 +18912,34 @@ SE_BIND_FUNC(js_gfx_Texture_resize) static bool js_gfx_Texture_computeHash(se::State& s) // NOLINT(readability-identifier-naming) { + CC_UNUSED bool ok = true; const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_computeHash : Error processing arguments"); - unsigned int result = cc::gfx::Texture::computeHash(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Texture_computeHash : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + do { + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + unsigned int result = cc::gfx::Texture::computeHash(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Texture_computeHash : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + } while (false); + do { + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + unsigned int result = cc::gfx::Texture::computeHash(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Texture_computeHash : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + } while (false); + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } SE_BIND_FUNC(js_gfx_Texture_computeHash) @@ -19940,17 +18973,13 @@ 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("info", _SE(js_gfx_Texture_getInfo), nullptr); + cls->defineProperty("viewInfo", _SE(js_gfx_Texture_getViewInfo), 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("height", _SE(js_gfx_Texture_getHeight), nullptr); + cls->defineProperty("format", _SE(js_gfx_Texture_getFormat), nullptr); cls->defineProperty("size", _SE(js_gfx_Texture_getSize), nullptr); + cls->defineProperty("hash", _SE(js_gfx_Texture_getHash), 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)); @@ -19965,27 +18994,469 @@ bool js_register_gfx_Texture(se::Object* obj) // NOLINT(readability-identifier-n se::ScriptEngine::getInstance()->clearException(); return true; } -se::Object* __jsb_cc_gfx_TextureBarrier_proto = nullptr; -se::Class* __jsb_cc_gfx_TextureBarrier_class = nullptr; +se::Object* __jsb_cc_gfx_Swapchain_proto = nullptr; +se::Class* __jsb_cc_gfx_Swapchain_class = nullptr; -static bool js_gfx_TextureBarrier_info(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Swapchain_createSurface(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_TextureBarrier_info : Invalid Native Object"); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_createSurface : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_createSurface : Error processing arguments"); + cobj->createSurface(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_createSurface) + +static bool js_gfx_Swapchain_destroy(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_destroy : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->destroy(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_destroy) + +static bool js_gfx_Swapchain_destroySurface(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_destroySurface : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cobj->destroySurface(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_destroySurface) + +static bool js_gfx_Swapchain_getColorTexture(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getColorTexture : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 0) { - const cc::gfx::TextureBarrierInfo& result = cobj->info(); + cc::gfx::Texture* result = cobj->getColorTexture(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_TextureBarrier_info : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getColorTexture : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } -SE_BIND_FUNC(js_gfx_TextureBarrier_info) +SE_BIND_PROP_GET(js_gfx_Swapchain_getColorTexture) + +static bool js_gfx_Swapchain_getDepthStencilTexture(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getDepthStencilTexture : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::gfx::Texture* result = cobj->getDepthStencilTexture(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getDepthStencilTexture : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Swapchain_getDepthStencilTexture) + +static bool js_gfx_Swapchain_getHeight(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getHeight : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getHeight(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getHeight : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Swapchain_getHeight) + +static bool js_gfx_Swapchain_getSurfaceTransform(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getSurfaceTransform : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + auto result = static_cast(cobj->getSurfaceTransform()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getSurfaceTransform : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Swapchain_getSurfaceTransform) + +static bool js_gfx_Swapchain_getVSyncMode(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getVSyncMode : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + auto result = static_cast(cobj->getVSyncMode()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getVSyncMode : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_getVSyncMode) + +static bool js_gfx_Swapchain_getWidth(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getWidth : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getWidth(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getWidth : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Swapchain_getWidth) + +static bool js_gfx_Swapchain_getWindowHandle(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_getWindowHandle : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + void* result = cobj->getWindowHandle(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_getWindowHandle : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_getWindowHandle) + +static bool js_gfx_Swapchain_initialize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_initialize : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_initialize : Error processing arguments"); + cobj->initialize(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_initialize) + +static bool js_gfx_Swapchain_resize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Swapchain_resize : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Swapchain_resize : Error processing arguments"); + cobj->resize(arg0.value(), arg1.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + return false; +} +SE_BIND_FUNC(js_gfx_Swapchain_resize) + +SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_Swapchain_finalize) + +static bool js_gfx_Swapchain_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c +{ + //#3 cc::gfx::Swapchain: is_skip_construtor True + se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::Swapchain constructor is skipped\")"); + return false; +} +SE_BIND_CTOR(js_gfx_Swapchain_constructor, __jsb_cc_gfx_Swapchain_class, js_cc_gfx_Swapchain_finalize) + + + +static bool js_cc_gfx_Swapchain_finalize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + auto* cobj = SE_THIS_OBJECT(s); + JSB_FREE(cobj); + } + return true; +} +SE_BIND_FINALIZE_FUNC(js_cc_gfx_Swapchain_finalize) + +bool js_register_gfx_Swapchain(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("Swapchain", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Swapchain_constructor)); + + cls->defineProperty("width", _SE(js_gfx_Swapchain_getWidth), nullptr); + cls->defineProperty("height", _SE(js_gfx_Swapchain_getHeight), nullptr); + cls->defineProperty("surfaceTransform", _SE(js_gfx_Swapchain_getSurfaceTransform), nullptr); + cls->defineProperty("colorTexture", _SE(js_gfx_Swapchain_getColorTexture), nullptr); + cls->defineProperty("depthStencilTexture", _SE(js_gfx_Swapchain_getDepthStencilTexture), nullptr); + cls->defineFunction("createSurface", _SE(js_gfx_Swapchain_createSurface)); + cls->defineFunction("destroy", _SE(js_gfx_Swapchain_destroy)); + cls->defineFunction("destroySurface", _SE(js_gfx_Swapchain_destroySurface)); + cls->defineFunction("getVSyncMode", _SE(js_gfx_Swapchain_getVSyncMode)); + cls->defineFunction("getWindowHandle", _SE(js_gfx_Swapchain_getWindowHandle)); + cls->defineFunction("initialize", _SE(js_gfx_Swapchain_initialize)); + cls->defineFunction("resize", _SE(js_gfx_Swapchain_resize)); + cls->defineFinalizeFunction(_SE(js_cc_gfx_Swapchain_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_gfx_Swapchain_proto = cls->getProto(); + __jsb_cc_gfx_Swapchain_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + return true; +} +se::Object* __jsb_cc_gfx_GlobalBarrier_proto = nullptr; +se::Class* __jsb_cc_gfx_GlobalBarrier_class = nullptr; + +static bool js_gfx_GlobalBarrier_getInfo(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_GlobalBarrier_getInfo : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + const cc::gfx::GlobalBarrierInfo& result = cobj->getInfo(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_getInfo : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_GlobalBarrier_getInfo) + +static bool js_gfx_GlobalBarrier_computeHash(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_computeHash : Error processing arguments"); + unsigned int result = cc::gfx::GlobalBarrier::computeHash(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_GlobalBarrier_computeHash : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_GlobalBarrier_computeHash) + +SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_GlobalBarrier_finalize) + +static bool js_gfx_GlobalBarrier_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c +{ + //#3 cc::gfx::GlobalBarrier: is_skip_construtor True + se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::GlobalBarrier constructor is skipped\")"); + return false; +} +SE_BIND_CTOR(js_gfx_GlobalBarrier_constructor, __jsb_cc_gfx_GlobalBarrier_class, js_cc_gfx_GlobalBarrier_finalize) + + + +static bool js_cc_gfx_GlobalBarrier_finalize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + auto* cobj = SE_THIS_OBJECT(s); + JSB_FREE(cobj); + } + return true; +} +SE_BIND_FINALIZE_FUNC(js_cc_gfx_GlobalBarrier_finalize) + +bool js_register_gfx_GlobalBarrier(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("GlobalBarrier", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_GlobalBarrier_constructor)); + + cls->defineFunction("getInfo", _SE(js_gfx_GlobalBarrier_getInfo)); + cls->defineStaticFunction("computeHash", _SE(js_gfx_GlobalBarrier_computeHash)); + cls->defineFinalizeFunction(_SE(js_cc_gfx_GlobalBarrier_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_gfx_GlobalBarrier_proto = cls->getProto(); + __jsb_cc_gfx_GlobalBarrier_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + return true; +} +se::Object* __jsb_cc_gfx_Sampler_proto = nullptr; +se::Class* __jsb_cc_gfx_Sampler_class = nullptr; + +static bool js_gfx_Sampler_getInfo(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Sampler_getInfo : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + const cc::gfx::SamplerInfo& result = cobj->getInfo(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Sampler_getInfo : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_PROP_GET(js_gfx_Sampler_getInfo) + +static bool js_gfx_Sampler_computeHash(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + SE_PRECONDITION2(ok, false, "js_gfx_Sampler_computeHash : Error processing arguments"); + unsigned int result = cc::gfx::Sampler::computeHash(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Sampler_computeHash : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_Sampler_computeHash) + +SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_Sampler_finalize) + +static bool js_gfx_Sampler_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c +{ + //#3 cc::gfx::Sampler: is_skip_construtor True + se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::Sampler constructor is skipped\")"); + return false; +} +SE_BIND_CTOR(js_gfx_Sampler_constructor, __jsb_cc_gfx_Sampler_class, js_cc_gfx_Sampler_finalize) + + + +static bool js_cc_gfx_Sampler_finalize(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) + { + se::NonRefNativePtrCreatedByCtorMap::erase(iter); + auto* cobj = SE_THIS_OBJECT(s); + JSB_FREE(cobj); + } + return true; +} +SE_BIND_FINALIZE_FUNC(js_cc_gfx_Sampler_finalize) + +bool js_register_gfx_Sampler(se::Object* obj) // NOLINT(readability-identifier-naming) +{ + auto* cls = se::Class::create("Sampler", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Sampler_constructor)); + + cls->defineProperty("info", _SE(js_gfx_Sampler_getInfo), nullptr); + cls->defineStaticFunction("computeHash", _SE(js_gfx_Sampler_computeHash)); + cls->defineFinalizeFunction(_SE(js_cc_gfx_Sampler_finalize)); + cls->install(); + JSBClassType::registerClass(cls); + + __jsb_cc_gfx_Sampler_proto = cls->getProto(); + __jsb_cc_gfx_Sampler_class = cls; + + se::ScriptEngine::getInstance()->clearException(); + return true; +} +se::Object* __jsb_cc_gfx_TextureBarrier_proto = nullptr; +se::Class* __jsb_cc_gfx_TextureBarrier_class = nullptr; + +static bool js_gfx_TextureBarrier_getInfo(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_TextureBarrier_getInfo : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + const cc::gfx::TextureBarrierInfo& result = cobj->getInfo(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_TextureBarrier_getInfo : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_TextureBarrier_getInfo) static bool js_gfx_TextureBarrier_computeHash(se::State& s) // NOLINT(readability-identifier-naming) { @@ -20009,12 +19480,11 @@ SE_BIND_FUNC(js_gfx_TextureBarrier_computeHash) SE_DECLARE_FINALIZE_FUNC(js_cc_gfx_TextureBarrier_finalize) -static bool js_gfx_TextureBarrier_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c +static bool js_gfx_TextureBarrier_constructor(se::State& /*s*/) // NOLINT(readability-identifier-naming) constructor.c { - cc::gfx::TextureBarrier* cobj = JSB_ALLOC(cc::gfx::TextureBarrier); - s.thisObject()->setPrivateData(cobj); - se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); - return true; + //#3 cc::gfx::TextureBarrier: is_skip_construtor True + se::ScriptEngine::getInstance()->evalString("throw new Error(\"cc::gfx::TextureBarrier constructor is skipped\")"); + return false; } SE_BIND_CTOR(js_gfx_TextureBarrier_constructor, __jsb_cc_gfx_TextureBarrier_class, js_cc_gfx_TextureBarrier_finalize) @@ -20037,7 +19507,7 @@ bool js_register_gfx_TextureBarrier(se::Object* obj) // NOLINT(readability-ident { auto* cls = se::Class::create("TextureBarrier", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_TextureBarrier_constructor)); - cls->defineFunction("info", _SE(js_gfx_TextureBarrier_info)); + cls->defineFunction("getInfo", _SE(js_gfx_TextureBarrier_getInfo)); cls->defineStaticFunction("computeHash", _SE(js_gfx_TextureBarrier_computeHash)); cls->defineFinalizeFunction(_SE(js_cc_gfx_TextureBarrier_finalize)); cls->install(); @@ -20054,15 +19524,37 @@ se::Class* __jsb_cc_gfx_Device_class = nullptr; static bool js_gfx_Device_acquire(se::State& s) // NOLINT(readability-identifier-naming) { + CC_UNUSED bool ok = true; auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_acquire : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_gfx_Device_acquire : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - if (argc == 0) { - cobj->acquire(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + do { + if (argc == 1) { + HolderType, true> arg0 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->acquire(arg0.value()); + return true; + } + } while(false); + + do { + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->acquire(arg0.value(), arg1.value()); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } SE_BIND_FUNC(js_gfx_Device_acquire) @@ -20178,29 +19670,6 @@ static bool js_gfx_Device_createFramebuffer(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_gfx_Device_createFramebuffer) -static bool js_gfx_Device_createGlobalBarrier(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_createGlobalBarrier : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Device_createGlobalBarrier : Error processing arguments"); - cc::gfx::GlobalBarrier* result = cobj->createGlobalBarrier(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_createGlobalBarrier : Error processing arguments"); - se::NonRefNativePtrCreatedByCtorMap::emplace(result); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_Device_createGlobalBarrier) - static bool js_gfx_Device_createInputAssembler(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20316,29 +19785,6 @@ static bool js_gfx_Device_createRenderPass(se::State& s) // NOLINT(readability-i } SE_BIND_FUNC(js_gfx_Device_createRenderPass) -static bool js_gfx_Device_createSampler(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_createSampler : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Device_createSampler : Error processing arguments"); - cc::gfx::Sampler* result = cobj->createSampler(arg0.value()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_createSampler : Error processing arguments"); - se::NonRefNativePtrCreatedByCtorMap::emplace(result); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_Device_createSampler) - static bool js_gfx_Device_createShader(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20362,6 +19808,29 @@ static bool js_gfx_Device_createShader(se::State& s) // NOLINT(readability-ident } SE_BIND_FUNC(js_gfx_Device_createShader) +static bool js_gfx_Device_createSwapchain(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Device_createSwapchain : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Device_createSwapchain : Error processing arguments"); + cc::gfx::Swapchain* result = cobj->createSwapchain(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Device_createSwapchain : Error processing arguments"); + se::NonRefNativePtrCreatedByCtorMap::emplace(result); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_Device_createSwapchain) + static bool js_gfx_Device_destroy(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20377,43 +19846,42 @@ static bool js_gfx_Device_destroy(se::State& s) // NOLINT(readability-identifier } SE_BIND_FUNC(js_gfx_Device_destroy) -static bool js_gfx_Device_devicePixelRatio(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Device_flushCommands(se::State& s) // NOLINT(readability-identifier-naming) { + CC_UNUSED bool ok = true; auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_devicePixelRatio : Invalid Native Object"); + SE_PRECONDITION2( cobj, false, "js_gfx_Device_flushCommands : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - float result = cobj->devicePixelRatio(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_devicePixelRatio : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_Device_devicePixelRatio) + do { + if (argc == 1) { + HolderType, true> arg0 = {}; -static bool js_gfx_Device_flushCommandsForJS(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_flushCommandsForJS : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 1) { - HolderType, true> arg0 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Device_flushCommandsForJS : Error processing arguments"); - cobj->flushCommandsForJS(arg0.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->flushCommands(arg0.value()); + return true; + } + } while(false); + + do { + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + if (!ok) { ok = true; break; } + ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); + if (!ok) { ok = true; break; } + cobj->flushCommands(arg0.value(), arg1.value()); + return true; + } + } while(false); + + SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc); return false; } -SE_BIND_FUNC(js_gfx_Device_flushCommandsForJS) +SE_BIND_FUNC(js_gfx_Device_flushCommands) static bool js_gfx_Device_getCapabilities(se::State& s) // NOLINT(readability-identifier-naming) { @@ -20434,25 +19902,6 @@ static bool js_gfx_Device_getCapabilities(se::State& s) // NOLINT(readability-id } SE_BIND_PROP_GET(js_gfx_Device_getCapabilities) -static bool js_gfx_Device_getColorFormat(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_getColorFormat : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getColorFormat()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_getColorFormat : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Device_getColorFormat) - static bool js_gfx_Device_getCommandBuffer(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20472,25 +19921,6 @@ static bool js_gfx_Device_getCommandBuffer(se::State& s) // NOLINT(readability-i } SE_BIND_PROP_GET(js_gfx_Device_getCommandBuffer) -static bool js_gfx_Device_getDepthStencilFormat(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_getDepthStencilFormat : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getDepthStencilFormat()); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_getDepthStencilFormat : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Device_getDepthStencilFormat) - static bool js_gfx_Device_getDeviceName(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20529,24 +19959,27 @@ static bool js_gfx_Device_getGfxAPI(se::State& s) // NOLINT(readability-identifi } SE_BIND_PROP_GET(js_gfx_Device_getGfxAPI) -static bool js_gfx_Device_getHeight(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Device_getGlobalBarrier(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_getHeight : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_gfx_Device_getGlobalBarrier : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getHeight(); + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getGlobalBarrier : Error processing arguments"); + cc::gfx::GlobalBarrier* result = cobj->getGlobalBarrier(arg0.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_getHeight : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getGlobalBarrier : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_PROP_GET(js_gfx_Device_getHeight) +SE_BIND_FUNC(js_gfx_Device_getGlobalBarrier) static bool js_gfx_Device_getMemoryStatus(se::State& s) // NOLINT(readability-identifier-naming) { @@ -20662,24 +20095,49 @@ static bool js_gfx_Device_getRenderer(se::State& s) // NOLINT(readability-identi } SE_BIND_PROP_GET(js_gfx_Device_getRenderer) -static bool js_gfx_Device_getSurfaceTransform(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_Device_getSampler(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_getSurfaceTransform : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_gfx_Device_getSampler : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 0) { - auto result = static_cast(cobj->getSurfaceTransform()); + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getSampler : Error processing arguments"); + cc::gfx::Sampler* result = cobj->getSampler(arg0.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_getSurfaceTransform : Error processing arguments"); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getSampler : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } -SE_BIND_PROP_GET(js_gfx_Device_getSurfaceTransform) +SE_BIND_FUNC(js_gfx_Device_getSampler) + +static bool js_gfx_Device_getTextureBarrier(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_Device_getTextureBarrier : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getTextureBarrier : Error processing arguments"); + cc::gfx::TextureBarrier* result = cobj->getTextureBarrier(arg0.value()); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_gfx_Device_getTextureBarrier : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_gfx_Device_getTextureBarrier) static bool js_gfx_Device_getVendor(se::State& s) // NOLINT(readability-identifier-naming) { @@ -20700,25 +20158,6 @@ static bool js_gfx_Device_getVendor(se::State& s) // NOLINT(readability-identifi } SE_BIND_PROP_GET(js_gfx_Device_getVendor) -static bool js_gfx_Device_getWidth(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_getWidth : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - unsigned int result = cobj->getWidth(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_gfx_Device_getWidth : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_PROP_GET(js_gfx_Device_getWidth) - static bool js_gfx_Device_hasFeature(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -20778,70 +20217,44 @@ static bool js_gfx_Device_present(se::State& s) // NOLINT(readability-identifier } SE_BIND_FUNC(js_gfx_Device_present) -static bool js_gfx_Device_resize(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_Device_resize : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); - ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_Device_resize : Error processing arguments"); - cobj->resize(arg0.value(), arg1.value()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; -} -SE_BIND_FUNC(js_gfx_Device_resize) - bool js_register_gfx_Device(se::Object* obj) // NOLINT(readability-identifier-naming) { 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("deviceName", _SE(js_gfx_Device_getDeviceName), nullptr); + cls->defineProperty("memoryStatus", _SE(js_gfx_Device_getMemoryStatus), 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("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("surfaceTransform", _SE(js_gfx_Device_getSurfaceTransform), nullptr); + cls->defineProperty("numTris", _SE(js_gfx_Device_getNumTris), 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)); cls->defineFunction("createDescriptorSet", _SE(js_gfx_Device_createDescriptorSet)); cls->defineFunction("createDescriptorSetLayout", _SE(js_gfx_Device_createDescriptorSetLayout)); cls->defineFunction("createFramebuffer", _SE(js_gfx_Device_createFramebuffer)); - cls->defineFunction("createGlobalBarrier", _SE(js_gfx_Device_createGlobalBarrier)); cls->defineFunction("createInputAssembler", _SE(js_gfx_Device_createInputAssembler)); cls->defineFunction("createPipelineLayout", _SE(js_gfx_Device_createPipelineLayout)); cls->defineFunction("createPipelineState", _SE(js_gfx_Device_createPipelineState)); cls->defineFunction("createQueue", _SE(js_gfx_Device_createQueue)); cls->defineFunction("createRenderPass", _SE(js_gfx_Device_createRenderPass)); - cls->defineFunction("createSampler", _SE(js_gfx_Device_createSampler)); cls->defineFunction("createShader", _SE(js_gfx_Device_createShader)); + cls->defineFunction("createSwapchain", _SE(js_gfx_Device_createSwapchain)); cls->defineFunction("destroy", _SE(js_gfx_Device_destroy)); - cls->defineFunction("devicePixelRatio", _SE(js_gfx_Device_devicePixelRatio)); - cls->defineFunction("flushCommands", _SE(js_gfx_Device_flushCommandsForJS)); + cls->defineFunction("flushCommands", _SE(js_gfx_Device_flushCommands)); + cls->defineFunction("getGlobalBarrier", _SE(js_gfx_Device_getGlobalBarrier)); + cls->defineFunction("getSampler", _SE(js_gfx_Device_getSampler)); + cls->defineFunction("getTextureBarrier", _SE(js_gfx_Device_getTextureBarrier)); cls->defineFunction("hasFeature", _SE(js_gfx_Device_hasFeature)); cls->defineFunction("initialize", _SE(js_gfx_Device_initialize)); cls->defineFunction("present", _SE(js_gfx_Device_present)); - cls->defineFunction("resize", _SE(js_gfx_Device_resize)); cls->install(); JSBClassType::registerClass(cls); @@ -20854,19 +20267,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) -{ - 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) { const auto& args = s.args(); @@ -20887,18 +20287,31 @@ static bool js_gfx_DeviceManager_create(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC(js_gfx_DeviceManager_create) -static bool js_gfx_DeviceManager_addCustomEvent(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_gfx_DeviceManager_destroy(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); size_t argc = args.size(); if (argc == 0) { - cc::gfx::DeviceManager::addCustomEvent(); + 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_addCustomEvent) +SE_BIND_FUNC(js_gfx_DeviceManager_destroy) + +static bool js_gfx_DeviceManager_addSurfaceEventListener(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::gfx::DeviceManager::addSurfaceEventListener(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_DeviceManager_addSurfaceEventListener) static bool js_cc_gfx_DeviceManager_finalize(se::State& s) // NOLINT(readability-identifier-naming) @@ -20918,9 +20331,9 @@ 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("addCustomEvent", _SE(js_gfx_DeviceManager_addCustomEvent)); + cls->defineStaticFunction("destroy", _SE(js_gfx_DeviceManager_destroy)); + cls->defineStaticFunction("addSurfaceEventListener", _SE(js_gfx_DeviceManager_addSurfaceEventListener)); cls->defineFinalizeFunction(_SE(js_cc_gfx_DeviceManager_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -20943,81 +20356,81 @@ bool register_all_gfx(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_gfx_ContextInfo(ns); + js_register_gfx_Size(ns); + js_register_gfx_DeviceCaps(ns); + js_register_gfx_Offset(ns); + js_register_gfx_Rect(ns); + js_register_gfx_Extent(ns); + js_register_gfx_TextureSubresLayers(ns); + js_register_gfx_TextureSubresRange(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_SwapchainInfo(ns); + js_register_gfx_DeviceInfo(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_GFXObject(ns); js_register_gfx_Buffer(ns); + js_register_gfx_InputAssembler(ns); + js_register_gfx_CommandBuffer(ns); + js_register_gfx_DescriptorSet(ns); + js_register_gfx_DescriptorSetLayout(ns); + js_register_gfx_Framebuffer(ns); + js_register_gfx_PipelineLayout(ns); + js_register_gfx_PipelineState(ns); + js_register_gfx_Queue(ns); + js_register_gfx_RenderPass(ns); + js_register_gfx_Shader(ns); + js_register_gfx_Texture(ns); + js_register_gfx_Swapchain(ns); + js_register_gfx_GlobalBarrier(ns); + js_register_gfx_Sampler(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_Offset(ns); - js_register_gfx_CommandBuffer(ns); - js_register_gfx_Framebuffer(ns); - js_register_gfx_Viewport(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_Color(ns); - js_register_gfx_Attribute(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_DescriptorSetLayout(ns); - js_register_gfx_TextureCopy(ns); - js_register_gfx_IndirectBuffer(ns); - js_register_gfx_Size(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_gfx_auto.h b/native/cocos/bindings/auto/jsb_gfx_auto.h index ba64d9c6fa..8b8177ddde 100644 --- a/native/cocos/bindings/auto/jsb_gfx_auto.h +++ b/native/cocos/bindings/auto/jsb_gfx_auto.h @@ -136,6 +136,26 @@ template<> bool sevalue_to_native(const se::Value &, cc::gfx::BindingMappingInfo *, se::Object *ctx); JSB_REGISTER_OBJECT_TYPE(cc::gfx::BindingMappingInfo); +extern se::Object* __jsb_cc_gfx_SwapchainInfo_proto; +extern se::Class* __jsb_cc_gfx_SwapchainInfo_class; + +bool js_register_cc_gfx_SwapchainInfo(se::Object* obj); +bool register_all_gfx(se::Object* obj); + +template<> +bool sevalue_to_native(const se::Value &, cc::gfx::SwapchainInfo *, se::Object *ctx); +JSB_REGISTER_OBJECT_TYPE(cc::gfx::SwapchainInfo); + +extern se::Object* __jsb_cc_gfx_DeviceInfo_proto; +extern se::Class* __jsb_cc_gfx_DeviceInfo_class; + +bool js_register_cc_gfx_DeviceInfo(se::Object* obj); +bool register_all_gfx(se::Object* obj); + +template<> +bool sevalue_to_native(const se::Value &, cc::gfx::DeviceInfo *, se::Object *ctx); +JSB_REGISTER_OBJECT_TYPE(cc::gfx::DeviceInfo); + extern se::Object* __jsb_cc_gfx_BufferInfo_proto; extern se::Class* __jsb_cc_gfx_BufferInfo_class; @@ -546,26 +566,6 @@ template<> bool sevalue_to_native(const se::Value &, cc::gfx::MemoryStatus *, se::Object *ctx); JSB_REGISTER_OBJECT_TYPE(cc::gfx::MemoryStatus); -extern se::Object* __jsb_cc_gfx_DeviceInfo_proto; -extern se::Class* __jsb_cc_gfx_DeviceInfo_class; - -bool js_register_cc_gfx_DeviceInfo(se::Object* obj); -bool register_all_gfx(se::Object* obj); - -template<> -bool sevalue_to_native(const se::Value &, cc::gfx::DeviceInfo *, se::Object *ctx); -JSB_REGISTER_OBJECT_TYPE(cc::gfx::DeviceInfo); - -extern se::Object* __jsb_cc_gfx_ContextInfo_proto; -extern se::Class* __jsb_cc_gfx_ContextInfo_class; - -bool js_register_cc_gfx_ContextInfo(se::Object* obj); -bool register_all_gfx(se::Object* obj); - -template<> -bool sevalue_to_native(const se::Value &, cc::gfx::ContextInfo *, se::Object *ctx); -JSB_REGISTER_OBJECT_TYPE(cc::gfx::ContextInfo); - extern se::Object* __jsb_cc_gfx_GFXObject_proto; extern se::Class* __jsb_cc_gfx_GFXObject_class; @@ -573,7 +573,6 @@ bool js_register_cc_gfx_GFXObject(se::Object* obj); bool register_all_gfx(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::gfx::GFXObject); -SE_DECLARE_FUNC(js_gfx_GFXObject_resizeObjectID); SE_DECLARE_FUNC(js_gfx_GFXObject_GFXObject); extern se::Object* __jsb_cc_gfx_Buffer_proto; @@ -608,8 +607,8 @@ bool register_all_gfx(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::gfx::CommandBuffer); SE_DECLARE_FUNC(js_gfx_CommandBuffer_begin); -SE_DECLARE_FUNC(js_gfx_CommandBuffer_beginRenderPassForJS); -SE_DECLARE_FUNC(js_gfx_CommandBuffer_bindDescriptorSetForJS); +SE_DECLARE_FUNC(js_gfx_CommandBuffer_beginRenderPass); +SE_DECLARE_FUNC(js_gfx_CommandBuffer_bindDescriptorSet); SE_DECLARE_FUNC(js_gfx_CommandBuffer_bindInputAssembler); SE_DECLARE_FUNC(js_gfx_CommandBuffer_bindPipelineState); SE_DECLARE_FUNC(js_gfx_CommandBuffer_blitTexture); @@ -636,18 +635,6 @@ SE_DECLARE_FUNC(js_gfx_CommandBuffer_setStencilWriteMask); SE_DECLARE_FUNC(js_gfx_CommandBuffer_setViewport); SE_DECLARE_FUNC(js_gfx_CommandBuffer_CommandBuffer); -extern se::Object* __jsb_cc_gfx_Context_proto; -extern se::Class* __jsb_cc_gfx_Context_class; - -bool js_register_cc_gfx_Context(se::Object* obj); -bool register_all_gfx(se::Object* obj); - -JSB_REGISTER_OBJECT_TYPE(cc::gfx::Context); -SE_DECLARE_FUNC(js_gfx_Context_destroy); -SE_DECLARE_FUNC(js_gfx_Context_initialize); -SE_DECLARE_FUNC(js_gfx_Context_present); -SE_DECLARE_FUNC(js_gfx_Context_Context); - extern se::Object* __jsb_cc_gfx_DescriptorSet_proto; extern se::Class* __jsb_cc_gfx_DescriptorSet_class; @@ -696,17 +683,6 @@ SE_DECLARE_FUNC(js_gfx_Framebuffer_initialize); SE_DECLARE_FUNC(js_gfx_Framebuffer_computeHash); SE_DECLARE_FUNC(js_gfx_Framebuffer_Framebuffer); -extern se::Object* __jsb_cc_gfx_GlobalBarrier_proto; -extern se::Class* __jsb_cc_gfx_GlobalBarrier_class; - -bool js_register_cc_gfx_GlobalBarrier(se::Object* obj); -bool register_all_gfx(se::Object* obj); - -JSB_REGISTER_OBJECT_TYPE(cc::gfx::GlobalBarrier); -SE_DECLARE_FUNC(js_gfx_GlobalBarrier_info); -SE_DECLARE_FUNC(js_gfx_GlobalBarrier_computeHash); -SE_DECLARE_FUNC(js_gfx_GlobalBarrier_GlobalBarrier); - extern se::Object* __jsb_cc_gfx_PipelineLayout_proto; extern se::Class* __jsb_cc_gfx_PipelineLayout_class; @@ -741,7 +717,7 @@ bool register_all_gfx(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::gfx::Queue); SE_DECLARE_FUNC(js_gfx_Queue_destroy); SE_DECLARE_FUNC(js_gfx_Queue_initialize); -SE_DECLARE_FUNC(js_gfx_Queue_submitForJS); +SE_DECLARE_FUNC(js_gfx_Queue_submit); SE_DECLARE_FUNC(js_gfx_Queue_Queue); extern se::Object* __jsb_cc_gfx_RenderPass_proto; @@ -759,17 +735,6 @@ SE_DECLARE_FUNC(js_gfx_RenderPass_initialize); SE_DECLARE_FUNC(js_gfx_RenderPass_computeHash); SE_DECLARE_FUNC(js_gfx_RenderPass_RenderPass); -extern se::Object* __jsb_cc_gfx_Sampler_proto; -extern se::Class* __jsb_cc_gfx_Sampler_class; - -bool js_register_cc_gfx_Sampler(se::Object* obj); -bool register_all_gfx(se::Object* obj); - -JSB_REGISTER_OBJECT_TYPE(cc::gfx::Sampler); -SE_DECLARE_FUNC(js_gfx_Sampler_destroy); -SE_DECLARE_FUNC(js_gfx_Sampler_initialize); -SE_DECLARE_FUNC(js_gfx_Sampler_Sampler); - extern se::Object* __jsb_cc_gfx_Shader_proto; extern se::Class* __jsb_cc_gfx_Shader_class; @@ -799,6 +764,43 @@ SE_DECLARE_FUNC(js_gfx_Texture_resize); SE_DECLARE_FUNC(js_gfx_Texture_computeHash); SE_DECLARE_FUNC(js_gfx_Texture_Texture); +extern se::Object* __jsb_cc_gfx_Swapchain_proto; +extern se::Class* __jsb_cc_gfx_Swapchain_class; + +bool js_register_cc_gfx_Swapchain(se::Object* obj); +bool register_all_gfx(se::Object* obj); + +JSB_REGISTER_OBJECT_TYPE(cc::gfx::Swapchain); +SE_DECLARE_FUNC(js_gfx_Swapchain_createSurface); +SE_DECLARE_FUNC(js_gfx_Swapchain_destroy); +SE_DECLARE_FUNC(js_gfx_Swapchain_destroySurface); +SE_DECLARE_FUNC(js_gfx_Swapchain_getVSyncMode); +SE_DECLARE_FUNC(js_gfx_Swapchain_getWindowHandle); +SE_DECLARE_FUNC(js_gfx_Swapchain_initialize); +SE_DECLARE_FUNC(js_gfx_Swapchain_resize); +SE_DECLARE_FUNC(js_gfx_Swapchain_Swapchain); + +extern se::Object* __jsb_cc_gfx_GlobalBarrier_proto; +extern se::Class* __jsb_cc_gfx_GlobalBarrier_class; + +bool js_register_cc_gfx_GlobalBarrier(se::Object* obj); +bool register_all_gfx(se::Object* obj); + +JSB_REGISTER_OBJECT_TYPE(cc::gfx::GlobalBarrier); +SE_DECLARE_FUNC(js_gfx_GlobalBarrier_getInfo); +SE_DECLARE_FUNC(js_gfx_GlobalBarrier_computeHash); +SE_DECLARE_FUNC(js_gfx_GlobalBarrier_GlobalBarrier); + +extern se::Object* __jsb_cc_gfx_Sampler_proto; +extern se::Class* __jsb_cc_gfx_Sampler_class; + +bool js_register_cc_gfx_Sampler(se::Object* obj); +bool register_all_gfx(se::Object* obj); + +JSB_REGISTER_OBJECT_TYPE(cc::gfx::Sampler); +SE_DECLARE_FUNC(js_gfx_Sampler_computeHash); +SE_DECLARE_FUNC(js_gfx_Sampler_Sampler); + extern se::Object* __jsb_cc_gfx_TextureBarrier_proto; extern se::Class* __jsb_cc_gfx_TextureBarrier_class; @@ -806,7 +808,7 @@ bool js_register_cc_gfx_TextureBarrier(se::Object* obj); bool register_all_gfx(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::gfx::TextureBarrier); -SE_DECLARE_FUNC(js_gfx_TextureBarrier_info); +SE_DECLARE_FUNC(js_gfx_TextureBarrier_getInfo); SE_DECLARE_FUNC(js_gfx_TextureBarrier_computeHash); SE_DECLARE_FUNC(js_gfx_TextureBarrier_TextureBarrier); @@ -823,21 +825,21 @@ SE_DECLARE_FUNC(js_gfx_Device_createCommandBuffer); SE_DECLARE_FUNC(js_gfx_Device_createDescriptorSet); SE_DECLARE_FUNC(js_gfx_Device_createDescriptorSetLayout); SE_DECLARE_FUNC(js_gfx_Device_createFramebuffer); -SE_DECLARE_FUNC(js_gfx_Device_createGlobalBarrier); SE_DECLARE_FUNC(js_gfx_Device_createInputAssembler); SE_DECLARE_FUNC(js_gfx_Device_createPipelineLayout); SE_DECLARE_FUNC(js_gfx_Device_createPipelineState); SE_DECLARE_FUNC(js_gfx_Device_createQueue); SE_DECLARE_FUNC(js_gfx_Device_createRenderPass); -SE_DECLARE_FUNC(js_gfx_Device_createSampler); SE_DECLARE_FUNC(js_gfx_Device_createShader); +SE_DECLARE_FUNC(js_gfx_Device_createSwapchain); SE_DECLARE_FUNC(js_gfx_Device_destroy); -SE_DECLARE_FUNC(js_gfx_Device_devicePixelRatio); -SE_DECLARE_FUNC(js_gfx_Device_flushCommandsForJS); +SE_DECLARE_FUNC(js_gfx_Device_flushCommands); +SE_DECLARE_FUNC(js_gfx_Device_getGlobalBarrier); +SE_DECLARE_FUNC(js_gfx_Device_getSampler); +SE_DECLARE_FUNC(js_gfx_Device_getTextureBarrier); SE_DECLARE_FUNC(js_gfx_Device_hasFeature); SE_DECLARE_FUNC(js_gfx_Device_initialize); SE_DECLARE_FUNC(js_gfx_Device_present); -SE_DECLARE_FUNC(js_gfx_Device_resize); extern se::Object* __jsb_cc_gfx_DeviceManager_proto; extern se::Class* __jsb_cc_gfx_DeviceManager_class; @@ -846,7 +848,7 @@ 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_addCustomEvent); +SE_DECLARE_FUNC(js_gfx_DeviceManager_destroy); +SE_DECLARE_FUNC(js_gfx_DeviceManager_addSurfaceEventListener); diff --git a/native/cocos/bindings/auto/jsb_physics_auto.cpp b/native/cocos/bindings/auto/jsb_physics_auto.cpp index 0192173ae1..fedd1092fa 100644 --- a/native/cocos/bindings/auto/jsb_physics_auto.cpp +++ b/native/cocos/bindings/auto/jsb_physics_auto.cpp @@ -4826,18 +4826,18 @@ bool register_all_physics(se::Object* obj) } se::Object* ns = nsVal.toObject(); + js_register_physics_World(ns); js_register_physics_RigidBody(ns); js_register_physics_SphereShape(ns); - js_register_physics_CylinderShape(ns); - js_register_physics_TrimeshShape(ns); - js_register_physics_PlaneShape(ns); - js_register_physics_DistanceJoint(ns); - js_register_physics_RevoluteJoint(ns); - js_register_physics_CapsuleShape(ns); js_register_physics_BoxShape(ns); - js_register_physics_World(ns); + js_register_physics_CapsuleShape(ns); + js_register_physics_PlaneShape(ns); + js_register_physics_TrimeshShape(ns); + js_register_physics_CylinderShape(ns); js_register_physics_ConeShape(ns); js_register_physics_TerrainShape(ns); + js_register_physics_RevoluteJoint(ns); + js_register_physics_DistanceJoint(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_pipeline_auto.cpp b/native/cocos/bindings/auto/jsb_pipeline_auto.cpp index a8449b7cdc..61d6d1221d 100644 --- a/native/cocos/bindings/auto/jsb_pipeline_auto.cpp +++ b/native/cocos/bindings/auto/jsb_pipeline_auto.cpp @@ -651,14 +651,17 @@ static bool js_pipeline_RenderPipeline_activate(se::State& s) // NOLINT(readabil const auto& args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; - if (argc == 0) { - bool result = cobj->activate(); + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_pipeline_RenderPipeline_activate : Error processing arguments"); + bool result = cobj->activate(arg0.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); SE_PRECONDITION2(ok, false, "js_pipeline_RenderPipeline_activate : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } SE_BIND_FUNC(js_pipeline_RenderPipeline_activate) @@ -773,6 +776,25 @@ static bool js_pipeline_RenderPipeline_getGlobalDSManager(se::State& s) // NOLIN } SE_BIND_PROP_GET(js_pipeline_RenderPipeline_getGlobalDSManager) +static bool js_pipeline_RenderPipeline_getProfiler(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_pipeline_RenderPipeline_getProfiler : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + cc::scene::Model* result = cobj->getProfiler(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_pipeline_RenderPipeline_getProfiler : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_pipeline_RenderPipeline_getProfiler) + static bool js_pipeline_RenderPipeline_getRenderstageByName(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -876,6 +898,25 @@ static bool js_pipeline_RenderPipeline_setPipelineSharedSceneData(se::State& s) } SE_BIND_FUNC(js_pipeline_RenderPipeline_setPipelineSharedSceneData) +static bool js_pipeline_RenderPipeline_setProfiler(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_pipeline_RenderPipeline_setProfiler : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + HolderType arg0 = {}; + ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_pipeline_RenderPipeline_setProfiler : Error processing arguments"); + cobj->setProfiler(arg0.value()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_pipeline_RenderPipeline_setProfiler) + static bool js_pipeline_RenderPipeline_setValue(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -927,11 +968,13 @@ bool js_register_pipeline_RenderPipeline(se::Object* obj) // NOLINT(readability- cls->defineFunction("activate", _SE(js_pipeline_RenderPipeline_activate)); cls->defineFunction("destroy", _SE(js_pipeline_RenderPipeline_destroy)); cls->defineFunction("getDevice", _SE(js_pipeline_RenderPipeline_getDevice)); + cls->defineFunction("getProfiler", _SE(js_pipeline_RenderPipeline_getProfiler)); cls->defineFunction("getRenderstageByName", _SE(js_pipeline_RenderPipeline_getRenderstageByName)); cls->defineFunction("initialize", _SE(js_pipeline_RenderPipeline_initialize)); cls->defineFunction("render", _SE(js_pipeline_RenderPipeline_render)); cls->defineFunction("resize", _SE(js_pipeline_RenderPipeline_resize)); cls->defineFunction("setPipelineSharedSceneData", _SE(js_pipeline_RenderPipeline_setPipelineSharedSceneData)); + cls->defineFunction("setProfiler", _SE(js_pipeline_RenderPipeline_setProfiler)); cls->defineFunction("setValue", _SE(js_pipeline_RenderPipeline_setValue)); cls->defineStaticFunction("getInstance", _SE(js_pipeline_RenderPipeline_getInstance)); cls->install(); @@ -1990,19 +2033,6 @@ static bool js_pipeline_InstancedBuffer_setDynamicOffset(se::State& s) // NOLINT } SE_BIND_FUNC(js_pipeline_InstancedBuffer_setDynamicOffset) -static bool js_pipeline_InstancedBuffer_destroyInstancedBuffer(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::pipeline::InstancedBuffer::destroyInstancedBuffer(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_pipeline_InstancedBuffer_destroyInstancedBuffer) - static bool js_pipeline_InstancedBuffer_get(se::State& s) // NOLINT(readability-identifier-naming) { CC_UNUSED bool ok = true; @@ -2040,6 +2070,19 @@ static bool js_pipeline_InstancedBuffer_get(se::State& s) // NOLINT(readability- } SE_BIND_FUNC(js_pipeline_InstancedBuffer_get) +static bool js_pipeline_InstancedBuffer_destroyInstancedBuffer(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::pipeline::InstancedBuffer::destroyInstancedBuffer(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_pipeline_InstancedBuffer_destroyInstancedBuffer) + SE_DECLARE_FINALIZE_FUNC(js_cc_pipeline_InstancedBuffer_finalize) static bool js_pipeline_InstancedBuffer_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c @@ -2077,8 +2120,8 @@ bool js_register_pipeline_InstancedBuffer(se::Object* obj) // NOLINT(readability cls->defineFunction("destroy", _SE(js_pipeline_InstancedBuffer_destroy)); cls->defineFunction("setDynamicOffset", _SE(js_pipeline_InstancedBuffer_setDynamicOffset)); - cls->defineStaticFunction("destroyInstancedBuffer", _SE(js_pipeline_InstancedBuffer_destroyInstancedBuffer)); cls->defineStaticFunction("get", _SE(js_pipeline_InstancedBuffer_get)); + cls->defineStaticFunction("destroyInstancedBuffer", _SE(js_pipeline_InstancedBuffer_destroyInstancedBuffer)); cls->defineFinalizeFunction(_SE(js_cc_pipeline_InstancedBuffer_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -2092,21 +2135,6 @@ bool js_register_pipeline_InstancedBuffer(se::Object* obj) // NOLINT(readability se::Object* __jsb_cc_pipeline_DeferredPipeline_proto = nullptr; se::Class* __jsb_cc_pipeline_DeferredPipeline_class = nullptr; -static bool js_pipeline_DeferredPipeline_destroyFrameGraphExternalTexture(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_pipeline_DeferredPipeline_destroyFrameGraphExternalTexture : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->destroyFrameGraphExternalTexture(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_pipeline_DeferredPipeline_destroyFrameGraphExternalTexture) - static bool js_pipeline_DeferredPipeline_getClearcolor(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); @@ -2205,36 +2233,6 @@ static bool js_pipeline_DeferredPipeline_getWidth(se::State& s) // NOLINT(readab } SE_BIND_FUNC(js_pipeline_DeferredPipeline_getWidth) -static bool js_pipeline_DeferredPipeline_initFrameGraphExternalTexture(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_pipeline_DeferredPipeline_initFrameGraphExternalTexture : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->initFrameGraphExternalTexture(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_pipeline_DeferredPipeline_initFrameGraphExternalTexture) - -static bool js_pipeline_DeferredPipeline_prepareFrameGraph(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_pipeline_DeferredPipeline_prepareFrameGraph : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cobj->prepareFrameGraph(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_pipeline_DeferredPipeline_prepareFrameGraph) - SE_DECLARE_FINALIZE_FUNC(js_cc_pipeline_DeferredPipeline_finalize) static bool js_pipeline_DeferredPipeline_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c @@ -2265,14 +2263,11 @@ bool js_register_pipeline_DeferredPipeline(se::Object* obj) // NOLINT(readabilit { auto* cls = se::Class::create("DeferredPipeline", obj, __jsb_cc_pipeline_RenderPipeline_proto, _SE(js_pipeline_DeferredPipeline_constructor)); - cls->defineFunction("destroyFrameGraphExternalTexture", _SE(js_pipeline_DeferredPipeline_destroyFrameGraphExternalTexture)); cls->defineFunction("getClearcolor", _SE(js_pipeline_DeferredPipeline_getClearcolor)); cls->defineFunction("getFrameGraph", _SE(js_pipeline_DeferredPipeline_getFrameGraph)); cls->defineFunction("getFrameGraphCamera", _SE(js_pipeline_DeferredPipeline_getFrameGraphCamera)); cls->defineFunction("getHeight", _SE(js_pipeline_DeferredPipeline_getHeight)); cls->defineFunction("getWidth", _SE(js_pipeline_DeferredPipeline_getWidth)); - cls->defineFunction("initFrameGraphExternalTexture", _SE(js_pipeline_DeferredPipeline_initFrameGraphExternalTexture)); - cls->defineFunction("prepareFrameGraph", _SE(js_pipeline_DeferredPipeline_prepareFrameGraph)); cls->defineFinalizeFunction(_SE(js_cc_pipeline_DeferredPipeline_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -2507,25 +2502,6 @@ bool js_register_pipeline_LightingStage(se::Object* obj) // NOLINT(readability-i se::Object* __jsb_cc_pipeline_PostprocessStage_proto = nullptr; se::Class* __jsb_cc_pipeline_PostprocessStage_class = nullptr; -static bool js_pipeline_PostprocessStage_getGlobalSet(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_pipeline_PostprocessStage_getGlobalSet : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - cc::gfx::DescriptorSet* result = cobj->getGlobalSet(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_pipeline_PostprocessStage_getGlobalSet : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_pipeline_PostprocessStage_getGlobalSet) - static bool js_pipeline_PostprocessStage_getInitializeInfo(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -2573,7 +2549,6 @@ bool js_register_pipeline_PostprocessStage(se::Object* obj) // NOLINT(readabilit { auto* cls = se::Class::create("PostprocessStage", obj, __jsb_cc_pipeline_RenderStage_proto, _SE(js_pipeline_PostprocessStage_constructor)); - cls->defineFunction("getGlobalSet", _SE(js_pipeline_PostprocessStage_getGlobalSet)); cls->defineStaticFunction("getInitializeInfo", _SE(js_pipeline_PostprocessStage_getInitializeInfo)); cls->defineFinalizeFunction(_SE(js_cc_pipeline_PostprocessStage_finalize)); cls->install(); @@ -2598,24 +2573,24 @@ bool register_all_pipeline(se::Object* obj) se::Object* ns = nsVal.toObject(); js_register_pipeline_RenderQueueDesc(ns); - js_register_pipeline_RenderFlow(ns); - js_register_pipeline_RenderStage(ns); - js_register_pipeline_LightingStage(ns); - js_register_pipeline_RenderPipeline(ns); - js_register_pipeline_RenderStageInfo(ns); - js_register_pipeline_ForwardPipeline(ns); - js_register_pipeline_GbufferStage(ns); - js_register_pipeline_RenderPipelineInfo(ns); - js_register_pipeline_ForwardStage(ns); - js_register_pipeline_ShadowStage(ns); js_register_pipeline_GlobalDSManager(ns); + js_register_pipeline_RenderPipelineInfo(ns); + js_register_pipeline_RenderPipeline(ns); + js_register_pipeline_ForwardPipeline(ns); js_register_pipeline_RenderFlowInfo(ns); - js_register_pipeline_PostprocessStage(ns); + js_register_pipeline_RenderFlow(ns); js_register_pipeline_ForwardFlow(ns); + js_register_pipeline_RenderStageInfo(ns); + js_register_pipeline_RenderStage(ns); + js_register_pipeline_ForwardStage(ns); + js_register_pipeline_ShadowFlow(ns); + js_register_pipeline_ShadowStage(ns); js_register_pipeline_InstancedBuffer(ns); js_register_pipeline_DeferredPipeline(ns); js_register_pipeline_MainFlow(ns); - js_register_pipeline_ShadowFlow(ns); + js_register_pipeline_GbufferStage(ns); + js_register_pipeline_LightingStage(ns); + js_register_pipeline_PostprocessStage(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_pipeline_auto.h b/native/cocos/bindings/auto/jsb_pipeline_auto.h index 6dcaa0c840..6ced9ff138 100644 --- a/native/cocos/bindings/auto/jsb_pipeline_auto.h +++ b/native/cocos/bindings/auto/jsb_pipeline_auto.h @@ -71,11 +71,13 @@ JSB_REGISTER_OBJECT_TYPE(cc::pipeline::RenderPipeline); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_activate); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_destroy); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_getDevice); +SE_DECLARE_FUNC(js_pipeline_RenderPipeline_getProfiler); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_getRenderstageByName); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_initialize); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_render); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_resize); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_setPipelineSharedSceneData); +SE_DECLARE_FUNC(js_pipeline_RenderPipeline_setProfiler); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_setValue); SE_DECLARE_FUNC(js_pipeline_RenderPipeline_getInstance); @@ -183,8 +185,8 @@ bool register_all_pipeline(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::pipeline::InstancedBuffer); SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_destroy); SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_setDynamicOffset); -SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_destroyInstancedBuffer); SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_get); +SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_destroyInstancedBuffer); SE_DECLARE_FUNC(js_pipeline_InstancedBuffer_InstancedBuffer); extern se::Object* __jsb_cc_pipeline_DeferredPipeline_proto; @@ -194,14 +196,11 @@ bool js_register_cc_pipeline_DeferredPipeline(se::Object* obj); bool register_all_pipeline(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::pipeline::DeferredPipeline); -SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_destroyFrameGraphExternalTexture); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_getClearcolor); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_getFrameGraph); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_getFrameGraphCamera); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_getHeight); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_getWidth); -SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_initFrameGraphExternalTexture); -SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_prepareFrameGraph); SE_DECLARE_FUNC(js_pipeline_DeferredPipeline_DeferredPipeline); extern se::Object* __jsb_cc_pipeline_MainFlow_proto; @@ -243,7 +242,6 @@ bool js_register_cc_pipeline_PostprocessStage(se::Object* obj); bool register_all_pipeline(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::pipeline::PostprocessStage); -SE_DECLARE_FUNC(js_pipeline_PostprocessStage_getGlobalSet); SE_DECLARE_FUNC(js_pipeline_PostprocessStage_getInitializeInfo); SE_DECLARE_FUNC(js_pipeline_PostprocessStage_PostprocessStage); diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index 2bd56ebea6..69c7e2e33a 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -6381,59 +6381,70 @@ bool js_register_scene_RenderScene(se::Object* obj) // NOLINT(readability-identi se::Object* __jsb_cc_scene_RenderWindow_proto = nullptr; se::Class* __jsb_cc_scene_RenderWindow_class = nullptr; -static bool js_scene_RenderWindow_get_hasOnScreenAttachments(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_scene_RenderWindow_getHeight(se::State& s) // NOLINT(readability-identifier-naming) { auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_get_hasOnScreenAttachments : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_getHeight : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getHeight(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_scene_RenderWindow_getHeight : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_scene_RenderWindow_getHeight) + +static bool js_scene_RenderWindow_getWidth(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_getWidth : Invalid Native Object"); + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + unsigned int result = cobj->getWidth(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_scene_RenderWindow_getWidth : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_scene_RenderWindow_getWidth) + +static bool js_scene_RenderWindow_get_swapchain(se::State& s) // NOLINT(readability-identifier-naming) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_get_swapchain : Invalid Native Object"); CC_UNUSED bool ok = true; se::Value jsret; - ok &= nativevalue_to_se(cobj->hasOnScreenAttachments, jsret, s.thisObject() /*ctx*/); + ok &= nativevalue_to_se(cobj->swapchain, jsret, s.thisObject() /*ctx*/); s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->hasOnScreenAttachments, s.thisObject(), s.rval()); + SE_HOLD_RETURN_VALUE(cobj->swapchain, s.thisObject(), s.rval()); return true; } -SE_BIND_PROP_GET(js_scene_RenderWindow_get_hasOnScreenAttachments) +SE_BIND_PROP_GET(js_scene_RenderWindow_get_swapchain) -static bool js_scene_RenderWindow_set_hasOnScreenAttachments(se::State& s) // NOLINT(readability-identifier-naming) +static bool js_scene_RenderWindow_set_swapchain(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_set_hasOnScreenAttachments : Invalid Native Object"); + SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_set_swapchain : Invalid Native Object"); CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->hasOnScreenAttachments, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_scene_RenderWindow_set_hasOnScreenAttachments : Error processing new value"); + ok &= sevalue_to_native(args[0], &cobj->swapchain, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_scene_RenderWindow_set_swapchain : Error processing new value"); return true; } -SE_BIND_PROP_SET(js_scene_RenderWindow_set_hasOnScreenAttachments) - -static bool js_scene_RenderWindow_get_hasOffScreenAttachments(se::State& s) // NOLINT(readability-identifier-naming) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_get_hasOffScreenAttachments : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->hasOffScreenAttachments, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->hasOffScreenAttachments, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_scene_RenderWindow_get_hasOffScreenAttachments) - -static bool js_scene_RenderWindow_set_hasOffScreenAttachments(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_scene_RenderWindow_set_hasOffScreenAttachments : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->hasOffScreenAttachments, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_scene_RenderWindow_set_hasOffScreenAttachments : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_scene_RenderWindow_set_hasOffScreenAttachments) +SE_BIND_PROP_SET(js_scene_RenderWindow_set_swapchain) static bool js_scene_RenderWindow_get_frameBuffer(se::State& s) // NOLINT(readability-identifier-naming) { @@ -6475,13 +6486,9 @@ bool sevalue_to_native(const se::Value &from, cc::scene::RenderWindow * to, se:: } se::Value field; bool ok = true; - json->getProperty("hasOnScreenAttachments", &field); + json->getProperty("swapchain", &field); if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->hasOnScreenAttachments), ctx); - } - json->getProperty("hasOffScreenAttachments", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->hasOffScreenAttachments), ctx); + ok &= sevalue_to_native(field, &(to->swapchain), ctx); } json->getProperty("frameBuffer", &field); if(!field.isNullOrUndefined()) { @@ -6526,13 +6533,10 @@ static bool js_scene_RenderWindow_constructor(se::State& s) // NOLINT(readabilit cc::scene::RenderWindow* cobj = JSB_ALLOC(cc::scene::RenderWindow); if (argc > 0 && !args[0].isUndefined()) { - ok &= sevalue_to_native(args[0], &(cobj->hasOnScreenAttachments), nullptr); + ok &= sevalue_to_native(args[0], &(cobj->swapchain), nullptr); } if (argc > 1 && !args[1].isUndefined()) { - ok &= sevalue_to_native(args[1], &(cobj->hasOffScreenAttachments), nullptr); - } - if (argc > 2 && !args[2].isUndefined()) { - ok &= sevalue_to_native(args[2], &(cobj->frameBuffer), nullptr); + ok &= sevalue_to_native(args[1], &(cobj->frameBuffer), nullptr); } if(!ok) { @@ -6566,9 +6570,10 @@ bool js_register_scene_RenderWindow(se::Object* obj) // NOLINT(readability-ident { auto* cls = se::Class::create("RenderWindow", obj, nullptr, _SE(js_scene_RenderWindow_constructor)); - cls->defineProperty("hasOnScreenAttachments", _SE(js_scene_RenderWindow_get_hasOnScreenAttachments), _SE(js_scene_RenderWindow_set_hasOnScreenAttachments)); - cls->defineProperty("hasOffScreenAttachments", _SE(js_scene_RenderWindow_get_hasOffScreenAttachments), _SE(js_scene_RenderWindow_set_hasOffScreenAttachments)); + cls->defineProperty("swapchain", _SE(js_scene_RenderWindow_get_swapchain), _SE(js_scene_RenderWindow_set_swapchain)); cls->defineProperty("frameBuffer", _SE(js_scene_RenderWindow_get_frameBuffer), _SE(js_scene_RenderWindow_set_frameBuffer)); + cls->defineFunction("getHeight", _SE(js_scene_RenderWindow_getHeight)); + cls->defineFunction("getWidth", _SE(js_scene_RenderWindow_getWidth)); cls->defineFinalizeFunction(_SE(js_cc_scene_RenderWindow_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -7527,35 +7532,35 @@ bool register_all_scene(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_scene_RenderScene(ns); - js_register_scene_Camera(ns); - js_register_scene_Fog(ns); js_register_scene_BaseNode(ns); + js_register_scene_Scene(ns); js_register_scene_Node(ns); - js_register_scene_Frustum(ns); - js_register_scene_DrawBatch2D(ns); js_register_scene_Light(ns); + js_register_scene_DirectionalLight(ns); + js_register_scene_Plane(ns); + js_register_scene_Frustum(ns); + js_register_scene_AABB(ns); + js_register_scene_SpotLight(ns); js_register_scene_SphereLight(ns); js_register_scene_Model(ns); - js_register_scene_BakedSkinningModel(ns); - js_register_scene_Plane(ns); - js_register_scene_JointTransform(ns); - js_register_scene_RenderWindow(ns); + js_register_scene_Fog(ns); js_register_scene_Shadow(ns); - js_register_scene_SubModel(ns); - js_register_scene_BakedJointInfo(ns); - js_register_scene_AABB(ns); - js_register_scene_Ambient(ns); - js_register_scene_SkinningModel(ns); - js_register_scene_DirectionalLight(ns); - js_register_scene_JointInfo(ns); - js_register_scene_Root(ns); - js_register_scene_Scene(ns); - js_register_scene_BakedAnimInfo(ns); - js_register_scene_Pass(ns); js_register_scene_Skybox(ns); + js_register_scene_Ambient(ns); js_register_scene_PipelineSharedSceneData(ns); - js_register_scene_SpotLight(ns); + js_register_scene_Root(ns); + js_register_scene_SubModel(ns); + js_register_scene_Pass(ns); + js_register_scene_BakedAnimInfo(ns); + js_register_scene_BakedJointInfo(ns); + js_register_scene_BakedSkinningModel(ns); + js_register_scene_DrawBatch2D(ns); + js_register_scene_JointTransform(ns); + js_register_scene_JointInfo(ns); + js_register_scene_SkinningModel(ns); + js_register_scene_RenderScene(ns); + js_register_scene_RenderWindow(ns); + js_register_scene_Camera(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_scene_auto.h b/native/cocos/bindings/auto/jsb_scene_auto.h index f86510b97b..53c5a9586f 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.h +++ b/native/cocos/bindings/auto/jsb_scene_auto.h @@ -410,6 +410,8 @@ bool register_all_scene(se::Object* obj); template<> bool sevalue_to_native(const se::Value &, cc::scene::RenderWindow *, se::Object *ctx); JSB_REGISTER_OBJECT_TYPE(cc::scene::RenderWindow); +SE_DECLARE_FUNC(js_scene_RenderWindow_getHeight); +SE_DECLARE_FUNC(js_scene_RenderWindow_getWidth); extern se::Object* __jsb_cc_scene_Camera_proto; extern se::Class* __jsb_cc_scene_Camera_class; diff --git a/native/cocos/bindings/auto/jsb_spine_auto.cpp b/native/cocos/bindings/auto/jsb_spine_auto.cpp index 47f535364e..024c170752 100644 --- a/native/cocos/bindings/auto/jsb_spine_auto.cpp +++ b/native/cocos/bindings/auto/jsb_spine_auto.cpp @@ -2921,23 +2921,6 @@ static bool js_spine_Bone_updateWorldTransform(se::State& s) // NOLINT(readabili } SE_BIND_FUNC(js_spine_Bone_updateWorldTransform) -static bool js_spine_Bone_isYDown(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 0) { - bool result = spine::Bone::isYDown(); - ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); - SE_PRECONDITION2(ok, false, "js_spine_Bone_isYDown : Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_spine_Bone_isYDown) - static bool js_spine_Bone_setYDown(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -2955,6 +2938,23 @@ static bool js_spine_Bone_setYDown(se::State& s) // NOLINT(readability-identifie } SE_BIND_FUNC(js_spine_Bone_setYDown) +static bool js_spine_Bone_isYDown(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 0) { + bool result = spine::Bone::isYDown(); + ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); + SE_PRECONDITION2(ok, false, "js_spine_Bone_isYDown : Error processing arguments"); + SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_spine_Bone_isYDown) + bool js_register_spine_Bone(se::Object* obj) // NOLINT(readability-identifier-naming) @@ -3019,8 +3019,8 @@ bool js_register_spine_Bone(se::Object* obj) // NOLINT(readability-identifier-na cls->defineFunction("setY", _SE(js_spine_Bone_setY)); cls->defineFunction("update", _SE(js_spine_Bone_update)); cls->defineFunction("updateWorldTransform", _SE(js_spine_Bone_updateWorldTransform)); - cls->defineStaticFunction("isYDown", _SE(js_spine_Bone_isYDown)); cls->defineStaticFunction("setYDown", _SE(js_spine_Bone_setYDown)); + cls->defineStaticFunction("isYDown", _SE(js_spine_Bone_isYDown)); cls->install(); JSBClassType::registerClass(cls); @@ -13458,7 +13458,7 @@ static bool js_spine_SkeletonRenderer_setAttachment(se::State& s) // NOLINT(read do { if (argc == 2) { HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg1 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -13638,7 +13638,7 @@ static bool js_spine_SkeletonRenderer_setSkin(se::State& s) // NOLINT(readabilit size_t argc = args.size(); do { if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -14902,44 +14902,6 @@ static bool js_spine_SkeletonAnimation_setTrackStartListener(se::State& s) // NO } SE_BIND_FUNC(js_spine_SkeletonAnimation_setTrackStartListener) -static bool js_spine_SkeletonAnimation_createWithBinaryFile(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; - if (argc == 2) { - HolderType arg0 = {}; - HolderType arg1 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - SE_PRECONDITION2(ok, false, "js_spine_SkeletonAnimation_createWithBinaryFile : Error processing arguments"); - auto result = spine::SkeletonAnimation::createWithBinaryFile(arg0.value(), arg1.value()); - result->retain(); - auto obj = se::Object::createObjectWithClass(__jsb_spine_SkeletonAnimation_class); - obj->setPrivateData(result); - s.rval().setObject(obj); - return true; - } - if (argc == 3) { - HolderType arg0 = {}; - HolderType arg1 = {}; - HolderType arg2 = {}; - ok &= sevalue_to_native(args[0], &arg0, nullptr); - ok &= sevalue_to_native(args[1], &arg1, nullptr); - ok &= sevalue_to_native(args[2], &arg2, nullptr); - SE_PRECONDITION2(ok, false, "js_spine_SkeletonAnimation_createWithBinaryFile : Error processing arguments"); - auto result = spine::SkeletonAnimation::createWithBinaryFile(arg0.value(), arg1.value(), arg2.value()); - result->retain(); - auto obj = se::Object::createObjectWithClass(__jsb_spine_SkeletonAnimation_class); - obj->setPrivateData(result); - s.rval().setObject(obj); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); - return false; -} -SE_BIND_FUNC(js_spine_SkeletonAnimation_createWithBinaryFile) - static bool js_spine_SkeletonAnimation_create(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -14996,6 +14958,44 @@ static bool js_spine_SkeletonAnimation_createWithJsonFile(se::State& s) // NOLIN } SE_BIND_FUNC(js_spine_SkeletonAnimation_createWithJsonFile) +static bool js_spine_SkeletonAnimation_createWithBinaryFile(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 2) { + HolderType arg0 = {}; + HolderType arg1 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + SE_PRECONDITION2(ok, false, "js_spine_SkeletonAnimation_createWithBinaryFile : Error processing arguments"); + auto result = spine::SkeletonAnimation::createWithBinaryFile(arg0.value(), arg1.value()); + result->retain(); + auto obj = se::Object::createObjectWithClass(__jsb_spine_SkeletonAnimation_class); + obj->setPrivateData(result); + s.rval().setObject(obj); + return true; + } + if (argc == 3) { + HolderType arg0 = {}; + HolderType arg1 = {}; + HolderType arg2 = {}; + ok &= sevalue_to_native(args[0], &arg0, nullptr); + ok &= sevalue_to_native(args[1], &arg1, nullptr); + ok &= sevalue_to_native(args[2], &arg2, nullptr); + SE_PRECONDITION2(ok, false, "js_spine_SkeletonAnimation_createWithBinaryFile : Error processing arguments"); + auto result = spine::SkeletonAnimation::createWithBinaryFile(arg0.value(), arg1.value(), arg2.value()); + result->retain(); + auto obj = se::Object::createObjectWithClass(__jsb_spine_SkeletonAnimation_class); + obj->setPrivateData(result); + s.rval().setObject(obj); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); + return false; +} +SE_BIND_FUNC(js_spine_SkeletonAnimation_createWithBinaryFile) + static bool js_spine_SkeletonAnimation_setGlobalTimeScale(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -15071,9 +15071,9 @@ bool js_register_spine_SkeletonAnimation(se::Object* obj) // NOLINT(readability- cls->defineFunction("setTrackInterruptListener", _SE(js_spine_SkeletonAnimation_setTrackInterruptListener)); cls->defineFunction("setTrackStartListener", _SE(js_spine_SkeletonAnimation_setTrackStartListener)); cls->defineFunction("ctor", _SE(js_spine_SkeletonAnimation_ctor)); - cls->defineStaticFunction("createWithBinaryFile", _SE(js_spine_SkeletonAnimation_createWithBinaryFile)); cls->defineStaticFunction("create", _SE(js_spine_SkeletonAnimation_create)); cls->defineStaticFunction("createWithJsonFile", _SE(js_spine_SkeletonAnimation_createWithJsonFile)); + cls->defineStaticFunction("createWithBinaryFile", _SE(js_spine_SkeletonAnimation_createWithBinaryFile)); cls->defineStaticFunction("setGlobalTimeScale", _SE(js_spine_SkeletonAnimation_setGlobalTimeScale)); cls->defineFinalizeFunction(_SE(js_spine_SkeletonAnimation_finalize)); cls->install(); @@ -15420,7 +15420,7 @@ static bool js_spine_SkeletonCacheAnimation_setAttachment(se::State& s) // NOLIN do { if (argc == 2) { HolderType arg0 = {}; - HolderType arg1 = {}; + HolderType arg1 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -15639,7 +15639,7 @@ static bool js_spine_SkeletonCacheAnimation_setSkin(se::State& s) // NOLINT(read size_t argc = args.size(); do { if (argc == 1) { - HolderType arg0 = {}; + HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); if (!ok) { ok = true; break; } @@ -15966,19 +15966,6 @@ static bool js_spine_SkeletonCacheMgr_removeSkeletonCache(se::State& s) // NOLIN } SE_BIND_FUNC(js_spine_SkeletonCacheMgr_removeSkeletonCache) -static bool js_spine_SkeletonCacheMgr_destroyInstance(se::State& s) // NOLINT(readability-identifier-naming) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - spine::SkeletonCacheMgr::destroyInstance(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_spine_SkeletonCacheMgr_destroyInstance) - static bool js_spine_SkeletonCacheMgr_getInstance(se::State& s) // NOLINT(readability-identifier-naming) { const auto& args = s.args(); @@ -15996,6 +15983,19 @@ static bool js_spine_SkeletonCacheMgr_getInstance(se::State& s) // NOLINT(readab } SE_BIND_FUNC(js_spine_SkeletonCacheMgr_getInstance) +static bool js_spine_SkeletonCacheMgr_destroyInstance(se::State& s) // NOLINT(readability-identifier-naming) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + spine::SkeletonCacheMgr::destroyInstance(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_spine_SkeletonCacheMgr_destroyInstance) + static bool js_spine_SkeletonCacheMgr_finalize(se::State& s) // NOLINT(readability-identifier-naming) { @@ -16016,8 +16016,8 @@ bool js_register_spine_SkeletonCacheMgr(se::Object* obj) // NOLINT(readability-i cls->defineFunction("buildSkeletonCache", _SE(js_spine_SkeletonCacheMgr_buildSkeletonCache)); cls->defineFunction("removeSkeletonCache", _SE(js_spine_SkeletonCacheMgr_removeSkeletonCache)); - cls->defineStaticFunction("destroyInstance", _SE(js_spine_SkeletonCacheMgr_destroyInstance)); cls->defineStaticFunction("getInstance", _SE(js_spine_SkeletonCacheMgr_getInstance)); + cls->defineStaticFunction("destroyInstance", _SE(js_spine_SkeletonCacheMgr_destroyInstance)); cls->defineFinalizeFunction(_SE(js_spine_SkeletonCacheMgr_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -16150,63 +16150,63 @@ bool register_all_spine(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_spine_Slot(ns); - js_register_spine_ConstraintData(ns); - js_register_spine_Polygon(ns); - js_register_spine_SkeletonCacheAnimation(ns); - js_register_spine_Attachment(ns); - js_register_spine_VertexAttachment(ns); - js_register_spine_SkeletonDataMgr(ns); - js_register_spine_VertexEffect(ns); - js_register_spine_JitterVertexEffect(ns); - js_register_spine_SkeletonCacheMgr(ns); - js_register_spine_Timeline(ns); - js_register_spine_CurveTimeline(ns); - js_register_spine_IkConstraintTimeline(ns); - js_register_spine_SkeletonRenderer(ns); js_register_spine_Animation(ns); - js_register_spine_MeshAttachment(ns); - js_register_spine_TranslateTimeline(ns); - js_register_spine_ShearTimeline(ns); + js_register_spine_TrackEntry(ns); + js_register_spine_AnimationState(ns); + js_register_spine_AnimationStateData(ns); + js_register_spine_Attachment(ns); + js_register_spine_Timeline(ns); js_register_spine_AttachmentTimeline(ns); + js_register_spine_Bone(ns); + js_register_spine_BoneData(ns); + js_register_spine_VertexAttachment(ns); + js_register_spine_BoundingBoxAttachment(ns); + js_register_spine_ClippingAttachment(ns); + js_register_spine_Color(ns); + js_register_spine_CurveTimeline(ns); + js_register_spine_ColorTimeline(ns); + js_register_spine_ConstraintData(ns); + js_register_spine_DeformTimeline(ns); + js_register_spine_DrawOrderTimeline(ns); + js_register_spine_Event(ns); + js_register_spine_EventData(ns); + js_register_spine_EventTimeline(ns); + js_register_spine_IkConstraint(ns); + js_register_spine_IkConstraintData(ns); + js_register_spine_IkConstraintTimeline(ns); + js_register_spine_MeshAttachment(ns); + js_register_spine_PathAttachment(ns); + js_register_spine_PathConstraint(ns); + js_register_spine_PathConstraintData(ns); js_register_spine_PathConstraintMixTimeline(ns); js_register_spine_PathConstraintPositionTimeline(ns); js_register_spine_PathConstraintSpacingTimeline(ns); - js_register_spine_SkeletonAnimation(ns); - js_register_spine_IkConstraintData(ns); - js_register_spine_SwirlVertexEffect(ns); - js_register_spine_AnimationStateData(ns); js_register_spine_PointAttachment(ns); - js_register_spine_AnimationState(ns); - js_register_spine_TrackEntry(ns); - js_register_spine_BoneData(ns); - js_register_spine_ScaleTimeline(ns); - js_register_spine_SkeletonData(ns); - js_register_spine_PathAttachment(ns); - js_register_spine_TransformConstraint(ns); - js_register_spine_BoundingBoxAttachment(ns); - js_register_spine_ClippingAttachment(ns); - js_register_spine_DeformTimeline(ns); - js_register_spine_SkeletonBounds(ns); - js_register_spine_TransformConstraintData(ns); - js_register_spine_ColorTimeline(ns); - js_register_spine_PathConstraint(ns); - js_register_spine_TransformConstraintTimeline(ns); - js_register_spine_Bone(ns); - js_register_spine_EventTimeline(ns); - js_register_spine_Skeleton(ns); - js_register_spine_TwoColorTimeline(ns); - js_register_spine_Color(ns); - js_register_spine_DrawOrderTimeline(ns); js_register_spine_RegionAttachment(ns); - js_register_spine_IkConstraint(ns); js_register_spine_RotateTimeline(ns); - js_register_spine_SlotData(ns); + js_register_spine_TranslateTimeline(ns); + js_register_spine_ScaleTimeline(ns); + js_register_spine_ShearTimeline(ns); + js_register_spine_Skeleton(ns); + js_register_spine_SkeletonBounds(ns); + js_register_spine_Polygon(ns); + js_register_spine_SkeletonData(ns); js_register_spine_Skin(ns); + js_register_spine_Slot(ns); + js_register_spine_SlotData(ns); + js_register_spine_TransformConstraint(ns); + js_register_spine_TransformConstraintData(ns); + js_register_spine_TransformConstraintTimeline(ns); + js_register_spine_TwoColorTimeline(ns); + js_register_spine_VertexEffect(ns); + js_register_spine_JitterVertexEffect(ns); + js_register_spine_SwirlVertexEffect(ns); js_register_spine_VertexEffectDelegate(ns); - js_register_spine_EventData(ns); - js_register_spine_Event(ns); - js_register_spine_PathConstraintData(ns); + js_register_spine_SkeletonRenderer(ns); + js_register_spine_SkeletonAnimation(ns); + js_register_spine_SkeletonCacheAnimation(ns); + js_register_spine_SkeletonCacheMgr(ns); + js_register_spine_SkeletonDataMgr(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_spine_auto.h b/native/cocos/bindings/auto/jsb_spine_auto.h index 43191dea27..f93e49071a 100644 --- a/native/cocos/bindings/auto/jsb_spine_auto.h +++ b/native/cocos/bindings/auto/jsb_spine_auto.h @@ -204,8 +204,8 @@ SE_DECLARE_FUNC(js_spine_Bone_setX); SE_DECLARE_FUNC(js_spine_Bone_setY); SE_DECLARE_FUNC(js_spine_Bone_update); SE_DECLARE_FUNC(js_spine_Bone_updateWorldTransform); -SE_DECLARE_FUNC(js_spine_Bone_isYDown); SE_DECLARE_FUNC(js_spine_Bone_setYDown); +SE_DECLARE_FUNC(js_spine_Bone_isYDown); extern se::Object* __jsb_spine_BoneData_proto; extern se::Class* __jsb_spine_BoneData_class; @@ -1080,9 +1080,9 @@ SE_DECLARE_FUNC(js_spine_SkeletonAnimation_setTrackEndListener); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_setTrackEventListener); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_setTrackInterruptListener); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_setTrackStartListener); -SE_DECLARE_FUNC(js_spine_SkeletonAnimation_createWithBinaryFile); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_create); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_createWithJsonFile); +SE_DECLARE_FUNC(js_spine_SkeletonAnimation_createWithBinaryFile); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_setGlobalTimeScale); SE_DECLARE_FUNC(js_spine_SkeletonAnimation_SkeletonAnimation); @@ -1137,8 +1137,8 @@ bool register_all_spine(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(spine::SkeletonCacheMgr); SE_DECLARE_FUNC(js_spine_SkeletonCacheMgr_buildSkeletonCache); SE_DECLARE_FUNC(js_spine_SkeletonCacheMgr_removeSkeletonCache); -SE_DECLARE_FUNC(js_spine_SkeletonCacheMgr_destroyInstance); SE_DECLARE_FUNC(js_spine_SkeletonCacheMgr_getInstance); +SE_DECLARE_FUNC(js_spine_SkeletonCacheMgr_destroyInstance); extern se::Object* __jsb_spine_SkeletonDataMgr_proto; extern se::Class* __jsb_spine_SkeletonDataMgr_class; diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 77d54e82c9..8723231746 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -942,7 +942,7 @@ inline bool sevalue_to_native(const se::Value &from, float *to, se::Object * /*c *to = from.toFloat(); return true; } -inline bool sevalue_to_native(const se::Value &from, double *to, se::Object * /*unused*/) { +inline bool sevalue_to_native(const se::Value &from, double *to, se::Object * /*unused*/) { // NOLINT(readability-identifier-naming) *to = from.toDouble(); return true; } @@ -1115,9 +1115,18 @@ bool sevalue_to_native(const se::Value &from, std::vector *to, se: template <> inline bool sevalue_to_native(const se::Value &from, void **to, se::Object * /*ctx*/) { - SE_LOGE("[warn] don't know how to convert to void *\n"); - *to = from.toObject()->getPrivateData(); - return true; + assert(to != nullptr); + if (from.isNumber()) { + // NOLINTNEXTLINE(performance-no-int-to-ptr) + *to = reinterpret_cast(from.toUint64()); + return true; + } + if (from.isObject()) { + *to = from.toObject()->getPrivateData(); + return true; + } + SE_LOGE("[warn] failed to convert to void *\n"); + return false; } template <> diff --git a/native/cocos/bindings/manual/jsb_gfx_manual.cpp b/native/cocos/bindings/manual/jsb_gfx_manual.cpp index a11d3871a2..7b372a3730 100644 --- a/native/cocos/bindings/manual/jsb_gfx_manual.cpp +++ b/native/cocos/bindings/manual/jsb_gfx_manual.cpp @@ -470,44 +470,6 @@ static bool js_gfx_CommandBuffer_copyBuffersToTexture(se::State &s) { // NOLINT( } SE_BIND_FUNC(js_gfx_CommandBuffer_copyBuffersToTexture) -static bool js_gfx_InputAssembler_extractDrawInfo(se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); - SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_extractDrawInfo : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - if (argc == 1) { - cc::gfx::DrawInfo nativeDrawInfo; - cobj->extractDrawInfo(nativeDrawInfo); - - se::Object *drawInfo = args[0].toObject(); - se::Value attrValue(nativeDrawInfo.vertexCount); - drawInfo->setProperty("vertexCount", attrValue); - - attrValue.setUint32(nativeDrawInfo.firstVertex); - drawInfo->setProperty("firstVertex", attrValue); - - attrValue.setUint32(nativeDrawInfo.indexCount); - drawInfo->setProperty("indexCount", attrValue); - - attrValue.setUint32(nativeDrawInfo.firstIndex); - drawInfo->setProperty("firstIndex", attrValue); - - attrValue.setUint32(nativeDrawInfo.vertexOffset); - drawInfo->setProperty("vertexOffset", attrValue); - - attrValue.setUint32(nativeDrawInfo.instanceCount); - drawInfo->setProperty("instanceCount", attrValue); - - attrValue.setUint32(nativeDrawInfo.firstInstance); - drawInfo->setProperty("firstInstance", attrValue); - - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; -} -SE_BIND_FUNC(js_gfx_InputAssembler_extractDrawInfo) - bool js_gfx_get_deviceInstance(se::State &s) { // NOLINT(readability-identifier-naming) nativevalue_to_se(cc::gfx::Device::getInstance(), s.rval(), nullptr); return true; @@ -528,8 +490,6 @@ bool register_all_gfx_manual(se::Object *obj) { __jsb_cc_gfx_CommandBuffer_proto->defineFunction("updateBuffer", _SE(js_gfx_CommandBuffer_updateBuffer)); __jsb_cc_gfx_CommandBuffer_proto->defineFunction("copyBuffersToTexture", _SE(js_gfx_CommandBuffer_copyBuffersToTexture)); - __jsb_cc_gfx_InputAssembler_proto->defineFunction("extractDrawInfo", _SE(js_gfx_InputAssembler_extractDrawInfo)); - __jsb_cc_gfx_Buffer_proto->defineFunction("initialize", _SE(js_gfx_Buffer_initialize)); __jsb_cc_gfx_Texture_proto->defineFunction("initialize", _SE(js_gfx_Texture_initialize)); diff --git a/native/cocos/platform/Application.cpp b/native/cocos/platform/Application.cpp index c9d73139cf..3f100c75ec 100644 --- a/native/cocos/platform/Application.cpp +++ b/native/cocos/platform/Application.cpp @@ -65,7 +65,7 @@ void Application::restartVM() { cc::EventDispatcher::init(); init(); - cc::gfx::DeviceManager::addCustomEvent(); + cc::gfx::DeviceManager::addSurfaceEventListener(); } void Application::close() { // NOLINT diff --git a/native/cocos/platform/Image.h b/native/cocos/platform/Image.h index ce534e8772..5a43da5f24 100644 --- a/native/cocos/platform/Image.h +++ b/native/cocos/platform/Image.h @@ -27,16 +27,13 @@ #pragma once -#include "base/Ref.h" -#include #include +#include +#include "base/Ref.h" +#include "gfx-base/GFXDef.h" namespace cc { -namespace gfx { -enum class Format; -} // namespace gfx - class Image : public Ref { public: Image(); @@ -72,17 +69,17 @@ public: // data will be free ouside. inline void takeData(unsigned char **outData) { *outData = _data; - _data = nullptr; + _data = nullptr; } // Getters inline unsigned char *getData() const { return _data; } - inline ssize_t getDataLen() const { return _dataLen; } - inline Format getFileType() const { return _fileType; } - inline gfx::Format getRenderFormat() const { return _renderFormat; } - inline int getWidth() const { return _width; } - inline int getHeight() const { return _height; } - inline std::string getFilePath() const { return _filePath; } + inline ssize_t getDataLen() const { return _dataLen; } + inline Format getFileType() const { return _fileType; } + inline gfx::Format getRenderFormat() const { return _renderFormat; } + inline int getWidth() const { return _width; } + inline int getHeight() const { return _height; } + inline std::string getFilePath() const { return _filePath; } inline bool isCompressed() const { return _isCompressed; } @@ -97,25 +94,25 @@ protected: bool initWithETC2Data(const unsigned char *data, ssize_t dataLen); bool initWithASTCData(const unsigned char *data, ssize_t dataLen); - unsigned char *_data = nullptr; - ssize_t _dataLen = 0; - int _width = 0; - int _height = 0; - Format _fileType = Format::UNKNOWN; - gfx::Format _renderFormat; - std::string _filePath; - bool _isCompressed = false; + unsigned char *_data = nullptr; + ssize_t _dataLen = 0; + int _width = 0; + int _height = 0; + Format _fileType = Format::UNKNOWN; + gfx::Format _renderFormat; + std::string _filePath; + bool _isCompressed = false; ~Image() override; static Format detectFormat(const unsigned char *data, ssize_t dataLen); - static bool isPng(const unsigned char *data, ssize_t dataLen); - static bool isJpg(const unsigned char *data, ssize_t dataLen); - static bool isWebp(const unsigned char *data, ssize_t dataLen); - static bool isPvr(const unsigned char *data, ssize_t dataLen); - static bool isEtc(const unsigned char *data, ssize_t dataLen); - static bool isEtc2(const unsigned char *data, ssize_t dataLen); - static bool isASTC(const unsigned char *data, ssize_t detaLen); + static bool isPng(const unsigned char *data, ssize_t dataLen); + static bool isJpg(const unsigned char *data, ssize_t dataLen); + static bool isWebp(const unsigned char *data, ssize_t dataLen); + static bool isPvr(const unsigned char *data, ssize_t dataLen); + static bool isEtc(const unsigned char *data, ssize_t dataLen); + static bool isEtc2(const unsigned char *data, ssize_t dataLen); + static bool isASTC(const unsigned char *data, ssize_t detaLen); static gfx::Format getASTCFormat(const unsigned char *pHeader); }; diff --git a/native/cocos/platform/mac/View.h b/native/cocos/platform/mac/View.h index 8c569f30c1..efc77635a2 100644 --- a/native/cocos/platform/mac/View.h +++ b/native/cocos/platform/mac/View.h @@ -24,9 +24,7 @@ ****************************************************************************/ #import -#ifdef CC_USE_METAL - #import -#endif +#import @interface View : NSView diff --git a/native/cocos/renderer/GFXDeviceManager.h b/native/cocos/renderer/GFXDeviceManager.h index fb07145ad8..d33888aa67 100644 --- a/native/cocos/renderer/GFXDeviceManager.h +++ b/native/cocos/renderer/GFXDeviceManager.h @@ -27,14 +27,17 @@ #include "bindings/event/CustomEventTypes.h" #include "bindings/event/EventDispatcher.h" + #include "gfx-agent/DeviceAgent.h" #include "gfx-empty/EmptyDevice.h" #include "gfx-validator/DeviceValidator.h" //#undef CC_USE_VULKAN +//#undef CC_USE_METAL //#undef CC_USE_GLES3 //#undef CC_USE_GLES2 + #ifdef CC_USE_VULKAN #include "gfx-vulkan/GFXVulkan.h" #endif @@ -89,14 +92,15 @@ public: static void destroy() { CC_SAFE_DESTROY(Device::instance); } - static void addCustomEvent() { + + static void addSurfaceEventListener() { Device *device = Device::instance; EventDispatcher::addCustomEventListener(EVENT_DESTROY_WINDOW, [device](const CustomEvent &e) -> void { - device->releaseSurface(reinterpret_cast(e.args->ptrVal)); + device->destroySurface(e.args->ptrVal); }); EventDispatcher::addCustomEventListener(EVENT_RECREATE_WINDOW, [device](const CustomEvent &e) -> void { - device->acquireSurface(reinterpret_cast(e.args->ptrVal)); + device->createSurface(e.args->ptrVal); }); } @@ -118,7 +122,7 @@ private: return false; } - addCustomEvent(); + addSurfaceEventListener(); *pDevice = device; return true; diff --git a/native/cocos/renderer/frame-graph/Blackboard.h b/native/cocos/renderer/frame-graph/Blackboard.h index fffbd41111..5c178166c5 100644 --- a/native/cocos/renderer/frame-graph/Blackboard.h +++ b/native/cocos/renderer/frame-graph/Blackboard.h @@ -42,7 +42,7 @@ public: Blackboard &operator=(Blackboard &&) = delete; inline ValueType &operator[](const KeyType &name) noexcept; - inline void put(const KeyType &name, ValueType const handle) noexcept; + inline void put(const KeyType &name, ValueType handle) noexcept; inline ValueType get(const KeyType &name) const noexcept; inline void clear() noexcept; inline bool has(const KeyType &name) const noexcept; diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index 7d1282e91d..b817dacc1f 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -26,19 +26,19 @@ #include "DevicePass.h" #include #include "CallbackPass.h" +#include "DevicePassResourceTable.h" #include "FrameGraph.h" #include "PassNode.h" #include "ResourceNode.h" #include "gfx-base/GFXCommandBuffer.h" -#include "DevicePassResourceTable.h" namespace cc { namespace framegraph { -DevicePass::DevicePass(const FrameGraph &graph, std::vector const &subPassNodes) { +DevicePass::DevicePass(const FrameGraph &graph, std::vector const &subpassNodes) { std::vector attachments; - for (const PassNode *const passNode : subPassNodes) { + for (const PassNode *passNode : subpassNodes) { append(graph, passNode, &attachments); } @@ -48,19 +48,19 @@ DevicePass::DevicePass(const FrameGraph &graph, std::vector const &s for (auto &attachment : attachments) { const ResourceNode &resourceNode = graph.getResourceNode(attachment.textureHandle); CC_ASSERT(resourceNode.virtualResource); + + gfx::Texture *resource = static_cast *>(resourceNode.virtualResource)->getDeviceResource(); + CC_ASSERT(resource); + _attachments.emplace_back(); _attachments.back().attachment = std::move(attachment); - _attachments.back().renderTarget = static_cast *>(resourceNode.virtualResource)->getDeviceResource(); - //CC_ASSERT(_attachments.back().renderTarget); // back buffer doesn't have a device resource instance, for now - renderTargets.emplace_back(_attachments.back().renderTarget); + _attachments.back().renderTarget = resource; + renderTargets.emplace_back(resource); } - bool const multiSubPass = subPassNodes.size() > 1; - - for (PassNode *const passNode : subPassNodes) { - _resourceTable.extract(graph, passNode, multiSubPass, renderTargets); + for (PassNode *const passNode : subpassNodes) { + _resourceTable.extract(graph, passNode, renderTargets); } - _resourceTable._devicePass = this; } void DevicePass::execute() { @@ -69,8 +69,8 @@ void DevicePass::execute() { begin(cmdBuff); for (size_t i = 0; i < _subpasses.size(); ++i) { - Subpass &subPass = _subpasses[i]; - for (LogicPass &pass : subPass.logicPasses) { + Subpass &subpass = _subpasses[i]; + for (LogicPass &pass : subpass.logicPasses) { gfx::Viewport &viewport = pass.customViewport ? pass.viewport : _viewport; gfx::Rect & scissor = pass.customViewport ? pass.scissor : _scissor; @@ -93,42 +93,63 @@ void DevicePass::execute() { } void DevicePass::append(const FrameGraph &graph, const PassNode *passNode, std::vector *attachments) { - _subpasses.emplace_back(); - Subpass &subPass = _subpasses.back(); + Subpass &subpass = _subpasses.emplace_back(); do { - subPass.logicPasses.emplace_back(); - LogicPass &logicPass = subPass.logicPasses.back(); + subpass.logicPasses.emplace_back(); + LogicPass &logicPass = subpass.logicPasses.back(); logicPass.pass = passNode->_pass.get(); logicPass.customViewport = passNode->_customViewport; logicPass.viewport = passNode->_viewport; logicPass.scissor = passNode->_scissor; - std::for_each(passNode->_attachments.begin(), passNode->_attachments.end(), [&, this](const RenderTargetAttachment &attachment) { - append(graph, attachment, attachments); - }); + for (const auto &attachment : passNode->_attachments) { + append(graph, attachment, attachments, &subpass.desc, passNode->_reads); + } + + for (const auto &handle : passNode->_reads) { + const auto it = std::find_if(attachments->begin(), attachments->end(), [&handle](const RenderTargetAttachment &attachment) { + return attachment.textureHandle == handle; + }); + if (it != attachments->end()) { + uint input = utils::toUint(it - attachments->begin()); + if (std::find(subpass.desc.inputs.begin(), subpass.desc.inputs.end(), input) == subpass.desc.inputs.end()) { + subpass.desc.inputs.push_back(input); + } + } + } passNode = passNode->_next; } while (passNode); } -void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &attachment, std::vector *attachments) { +void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &attachment, + std::vector *attachments, gfx::SubpassInfo *subpass, const std::vector &reads) { auto it = std::find_if(attachments->begin(), attachments->end(), [&attachment](const RenderTargetAttachment &x) { return attachment.desc.usage == x.desc.usage && attachment.desc.slot == x.desc.slot; }); + RenderTargetAttachment *output{nullptr}; + if (it == attachments->end()) { - attachments->emplace_back(attachment); + output = &attachments->emplace_back(attachment); _usedRenderTargetSlotMask |= 1 << attachment.desc.slot; } else { const ResourceNode &resourceNodeA = graph.getResourceNode(it->textureHandle); const ResourceNode &resourceNodeB = graph.getResourceNode(attachment.textureHandle); if (resourceNodeA.virtualResource == resourceNodeB.virtualResource) { - if (attachment.storeOp != gfx::StoreOp::DISCARD) it->storeOp = attachment.storeOp; + output = &*it; + if (attachment.storeOp != gfx::StoreOp::DISCARD) { + output->storeOp = attachment.storeOp; + output->desc.endAccesses = attachment.desc.endAccesses; + } + if (std::find(reads.begin(), reads.end(), output->textureHandle) != reads.end()) { + output->isGeneralLayout = true; // it's an 'inout' attachment + } } else { CC_ASSERT(attachment.desc.usage == RenderTargetAttachment::Usage::COLOR); - attachments->emplace_back(attachment); + output = &attachments->emplace_back(attachment); for (uint8_t i = 0; i < RenderTargetAttachment::DEPTH_STENCIL_SLOT_START; ++i) { if ((_usedRenderTargetSlotMask & (1 << i)) == 0) { @@ -138,10 +159,14 @@ void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &a } } } -} -const RenderPass &DevicePassResourceTable::getRenderPass() const { - return _devicePass->getRenderPass(); + if (attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { + if (std::find(subpass->colors.begin(), subpass->colors.end(), output->desc.slot) == subpass->colors.end()) { + subpass->colors.push_back(output->desc.slot); + } + } else { + subpass->depthStencil = output->desc.slot; + } } void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { @@ -155,35 +180,46 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { clearColors.clear(); _viewport = gfx::Viewport(); _scissor = gfx::Rect(); + for (const auto &attachElem : _attachments) { gfx::Texture *attachment = attachElem.renderTarget; if (attachElem.attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { - rpInfo.colorAttachments.emplace_back(); - rpInfo.colorAttachments.back().format = attachment ? attachment->getFormat() : gfx::Device::getInstance()->getColorFormat(); - rpInfo.colorAttachments.back().loadOp = attachElem.attachment.desc.loadOp; - rpInfo.colorAttachments.back().storeOp = attachElem.attachment.storeOp; - rpInfo.colorAttachments.back().beginAccesses = attachElem.attachment.desc.beginAccesses; - rpInfo.colorAttachments.back().endAccesses = attachElem.attachment.desc.endAccesses; + auto &attachmentInfo = rpInfo.colorAttachments.emplace_back(); + attachmentInfo.format = attachment->getFormat(); + attachmentInfo.loadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.storeOp = attachElem.attachment.storeOp; + attachmentInfo.beginAccesses = attachElem.attachment.desc.beginAccesses; + attachmentInfo.endAccesses = attachElem.attachment.desc.endAccesses; + attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; fboInfo.colorTextures.push_back(attachElem.renderTarget); + _viewport.width = _scissor.width = attachment->getWidth(); + _viewport.height = _scissor.height = attachment->getHeight(); clearColors.emplace_back(attachElem.attachment.desc.clearColor); - _viewport.width = _scissor.width = attachment ? attachment->getWidth() : gfx::Device::getInstance()->getWidth(); - _viewport.height = _scissor.height = attachment ? attachment->getHeight() : gfx::Device::getInstance()->getHeight(); } else { - rpInfo.depthStencilAttachment.format = attachment ? attachment->getFormat() : gfx::Device::getInstance()->getDepthStencilFormat(); - rpInfo.depthStencilAttachment.depthLoadOp = attachElem.attachment.desc.loadOp; - rpInfo.depthStencilAttachment.depthStoreOp = attachElem.attachment.storeOp; - rpInfo.depthStencilAttachment.stencilLoadOp = attachElem.attachment.desc.loadOp; - rpInfo.depthStencilAttachment.stencilStoreOp = attachElem.attachment.storeOp; - rpInfo.depthStencilAttachment.beginAccesses = attachElem.attachment.desc.beginAccesses; - rpInfo.depthStencilAttachment.endAccesses = attachElem.attachment.desc.endAccesses; - fboInfo.depthStencilTexture = attachElem.renderTarget; - clearDepth = attachElem.attachment.desc.clearDepth; - clearStencil = attachElem.attachment.desc.clearStencil; + auto &attachmentInfo = rpInfo.depthStencilAttachment; + attachmentInfo.format = attachment->getFormat(); + attachmentInfo.depthLoadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.stencilLoadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.depthStoreOp = attachElem.attachment.storeOp; + attachmentInfo.stencilStoreOp = attachElem.attachment.storeOp; + attachmentInfo.beginAccesses = attachElem.attachment.desc.beginAccesses; + attachmentInfo.endAccesses = attachElem.attachment.desc.endAccesses; + attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; + fboInfo.depthStencilTexture = attachElem.renderTarget; + _viewport.width = _scissor.width = attachment->getWidth(); + _viewport.height = _scissor.height = attachment->getHeight(); + clearDepth = attachElem.attachment.desc.clearDepth; + clearStencil = attachElem.attachment.desc.clearStencil; } } + for (auto &subpass : _subpasses) { + rpInfo.subpasses.emplace_back(subpass.desc); + } + _renderPass = RenderPass(rpInfo); _renderPass.createTransient(); + _resourceTable._renderPass = _renderPass.get(); fboInfo.renderPass = _renderPass.get(); _fbo = Framebuffer(fboInfo); diff --git a/native/cocos/renderer/frame-graph/DevicePass.h b/native/cocos/renderer/frame-graph/DevicePass.h index 1f43067bce..861846dd82 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.h +++ b/native/cocos/renderer/frame-graph/DevicePass.h @@ -37,7 +37,7 @@ namespace framegraph { class DevicePass final { public: DevicePass() = delete; - DevicePass(const FrameGraph &graph, std::vector const &subPassNodes); + DevicePass(const FrameGraph &graph, std::vector const &subpassNodes); DevicePass(const DevicePass &) = delete; DevicePass(DevicePass &&) = delete; ~DevicePass() = default; @@ -45,7 +45,6 @@ public: DevicePass &operator=(DevicePass &&) = delete; void execute(); - const RenderPass &getRenderPass() const { return _renderPass; } private: struct LogicPass final { @@ -57,6 +56,7 @@ private: struct Subpass final { std::vector logicPasses{}; + gfx::SubpassInfo desc; }; struct Attachment final { @@ -65,7 +65,8 @@ private: }; void append(const FrameGraph &graph, const PassNode *passNode, std::vector *attachments); - void append(const FrameGraph &graph, const RenderTargetAttachment &attachment, std::vector *attachments); + void append(const FrameGraph &graph, const RenderTargetAttachment &attachment, + std::vector *attachments, gfx::SubpassInfo *subpass, const std::vector &reads); void begin(gfx::CommandBuffer *cmdBuff); void next(gfx::CommandBuffer *cmdBuff) noexcept; void end(gfx::CommandBuffer *cmdBuff); diff --git a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp index eaf9639a60..635dde708f 100644 --- a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp +++ b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp @@ -25,9 +25,9 @@ #include "DevicePassResourceTable.h" +#include #include "FrameGraph.h" #include "PassNode.h" -#include namespace cc { namespace framegraph { @@ -38,15 +38,14 @@ gfx::GFXObject *DevicePassResourceTable::get(const ResourceDictionary &from, Han } void DevicePassResourceTable::extract(const FrameGraph & graph, - const PassNode *const passNode, - bool multiSubPass, + const PassNode * passNode, std::vector const &renderTargets) noexcept { - extract(graph, passNode->_reads, _reads, multiSubPass, renderTargets); - extract(graph, passNode->_writes, _writes, true, renderTargets); + do { + extract(graph, passNode->_reads, _reads, false, renderTargets); + extract(graph, passNode->_writes, _writes, true, renderTargets); - if (passNode->_next) { - extract(graph, passNode->_next, multiSubPass, renderTargets); - } + passNode = passNode->_next; + } while (passNode); } void DevicePassResourceTable::extract(const FrameGraph & graph, @@ -81,9 +80,7 @@ void DevicePassResourceTable::extract(const FrameGraph & g } } - if (deviceResource) { - to.emplace(handle, deviceResource); - } + to[handle] = deviceResource; }); } diff --git a/native/cocos/renderer/frame-graph/DevicePassResourceTable.h b/native/cocos/renderer/frame-graph/DevicePassResourceTable.h index 7d94ac90f6..ee8b61ebf7 100644 --- a/native/cocos/renderer/frame-graph/DevicePassResourceTable.h +++ b/native/cocos/renderer/frame-graph/DevicePassResourceTable.h @@ -25,10 +25,10 @@ #pragma once +#include #include "Handle.h" #include "RenderTargetAttachment.h" #include "Resource.h" -#include namespace cc { namespace framegraph { @@ -54,19 +54,20 @@ public: std::enable_if_t::value, typename Type::DeviceResource *> getWrite(TypedHandle handle) const noexcept; - const RenderPass &getRenderPass() const; + gfx::RenderPass *getRenderPass() const { return _renderPass; } private: using ResourceDictionary = std::unordered_map; static gfx::GFXObject *get(const ResourceDictionary &from, Handle handle) noexcept; - void extract(const FrameGraph &graph, const PassNode *const passNode, bool multiSubPass, std::vector const &renderTargets) noexcept; - void extract(const FrameGraph &graph, std::vector const &from, ResourceDictionary &to, bool ignoreRenderTarget, std::vector const &renderTargets) noexcept; + void extract(const FrameGraph &graph, const PassNode *passNode, std::vector const &renderTargets) noexcept; + static void extract(const FrameGraph &graph, std::vector const &from, ResourceDictionary &to, bool ignoreRenderTarget, std::vector const &renderTargets) noexcept; ResourceDictionary _reads{}; ResourceDictionary _writes{}; - DevicePass *_devicePass = nullptr; + gfx::RenderPass *_renderPass{nullptr}; + friend class DevicePass; }; diff --git a/native/cocos/renderer/frame-graph/FrameGraph.cpp b/native/cocos/renderer/frame-graph/FrameGraph.cpp index 8785a07c7a..e81a00b569 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.cpp +++ b/native/cocos/renderer/frame-graph/FrameGraph.cpp @@ -35,7 +35,7 @@ namespace cc { namespace framegraph { namespace { -// using function scoped static member +// use function scoped static member // to ensure correct initialization order StringPool &getStringPool() { static StringPool pool; @@ -55,7 +55,7 @@ const char *FrameGraph::handleToString(const StringHandle &handle) noexcept { return getStringPool().handleToString(handle); } -void FrameGraph::present(const TextureHandle &input) { +void FrameGraph::present(const TextureHandle &input, gfx::Texture *target) { static const StringHandle S_NAME_PRESENT = FrameGraph::stringToHandle("Present"); const ResourceNode & resourceNode = getResourceNode(input); CC_ASSERT(resourceNode.writer); @@ -70,32 +70,32 @@ void FrameGraph::present(const TextureHandle &input) { data.input = builder.read(input); builder.sideEffect(); }, - [](const PassDataPresent &data, const DevicePassResourceTable &table) { + [target](const PassDataPresent &data, const DevicePassResourceTable &table) { auto *cmdBuff = gfx::Device::getInstance()->getCommandBuffer(); gfx::Texture *input = table.getRead(data.input); - if (input) { + if (input && input != target) { gfx::TextureBlit region; region.srcExtent.width = input->getWidth(); region.srcExtent.height = input->getHeight(); region.dstExtent.width = input->getWidth(); region.dstExtent.height = input->getHeight(); - cmdBuff->blitTexture(input, nullptr, ®ion, 1, gfx::Filter::POINT); + cmdBuff->blitTexture(input, target, ®ion, 1, gfx::Filter::POINT); } }); } -void FrameGraph::presentLastVersion(const VirtualResource *const virtualResource) { +void FrameGraph::presentLastVersion(const VirtualResource *const virtualResource, gfx::Texture *target) { const auto it = std::find_if(_resourceNodes.rbegin(), _resourceNodes.rend(), [&virtualResource](const ResourceNode &node) { return node.virtualResource == virtualResource; }); CC_ASSERT(it != _resourceNodes.rend()); - present(TextureHandle(static_cast(it.base() - _resourceNodes.begin() - 1))); + present(TextureHandle(static_cast(it.base() - _resourceNodes.begin() - 1)), target); } -void FrameGraph::presentFromBlackboard(const StringHandle &inputName) { - present(TextureHandle(_blackboard.get(inputName))); +void FrameGraph::presentFromBlackboard(const StringHandle &inputName, gfx::Texture *target) { + present(TextureHandle(_blackboard.get(inputName)), target); } void FrameGraph::compile() { @@ -416,8 +416,7 @@ void FrameGraph::computeStoreActionAndMemoryless() { const gfx::TextureInfo &textureDesc = static_cast *>(renderTarget)->get().getDesc(); renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored; - renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::X1 && renderTarget->_writerCount < 2; - // TODO(minggo): memoryless gfx::Texture + renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::ONE && renderTarget->_writerCount < 2; } } @@ -429,8 +428,8 @@ void FrameGraph::generateDevicePasses() { ID passId = 1; - static std::vector subPassNodes; - subPassNodes.clear(); + static std::vector subpassNodes; + subpassNodes.clear(); for (const auto &passNode : _passNodes) { if (passNode->_refCount == 0) { @@ -438,25 +437,25 @@ void FrameGraph::generateDevicePasses() { } if (passId != passNode->_devicePassId) { - _devicePasses.emplace_back(new DevicePass(*this, subPassNodes)); + _devicePasses.emplace_back(new DevicePass(*this, subpassNodes)); - for (PassNode *const p : subPassNodes) { + for (PassNode *const p : subpassNodes) { p->releaseTransientResources(); } - subPassNodes.clear(); + subpassNodes.clear(); passId = passNode->_devicePassId; } passNode->requestTransientResources(); - subPassNodes.emplace_back(passNode.get()); + subpassNodes.emplace_back(passNode.get()); } - CC_ASSERT(subPassNodes.size() == 1); + CC_ASSERT(subpassNodes.size() == 1); - _devicePasses.emplace_back(new DevicePass(*this, subPassNodes)); + _devicePasses.emplace_back(new DevicePass(*this, subpassNodes)); - for (PassNode *const p : subPassNodes) { + for (PassNode *const p : subpassNodes) { p->releaseTransientResources(); } } @@ -529,7 +528,7 @@ void FrameGraph::exportGraphViz(const std::string &path) { if (attachment) { switch (attachment->desc.loadOp) { case gfx::LoadOp::DISCARD: - out << "Discard"; + out << "DontCare"; break; case gfx::LoadOp::CLEAR: out << "Clear"; @@ -547,8 +546,9 @@ void FrameGraph::exportGraphViz(const std::string &path) { } out << "\", style=filled, fillcolor=" - << ((node.virtualResource->isImported()) ? (node.virtualResource->_refCount ? "palegreen" : "palegreen4") : node.version == 0 ? "pink" - : (node.virtualResource->_refCount ? "skyblue" : "skyblue4")) + << ((node.virtualResource->isImported()) + ? (node.virtualResource->_refCount ? "palegreen" : "palegreen4") + : (node.version == 0 ? "pink" : (node.virtualResource->_refCount ? "skyblue" : "skyblue4"))) << "]\n"; } diff --git a/native/cocos/renderer/frame-graph/FrameGraph.h b/native/cocos/renderer/frame-graph/FrameGraph.h index 413293b630..b72bcd4cdf 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.h +++ b/native/cocos/renderer/frame-graph/FrameGraph.h @@ -53,9 +53,9 @@ public: static StringHandle stringToHandle(const char *name); static const char * handleToString(const StringHandle &handle) noexcept; - void present(const TextureHandle &input); - void presentLastVersion(const VirtualResource *virtualResource); - void presentFromBlackboard(const StringHandle &inputName); + void present(const TextureHandle &input, gfx::Texture *target); + void presentLastVersion(const VirtualResource *virtualResource, gfx::Texture *target); + void presentFromBlackboard(const StringHandle &inputName, gfx::Texture *target); void compile(); void execute() noexcept; void reset() noexcept; @@ -121,7 +121,7 @@ TypedHandle FrameGraph::create(const StringHandle &name, const typ template TypedHandle FrameGraph::importExternal(const StringHandle &name, ResourceType &resource) noexcept { - //CC_ASSERT(resource.Get()); // back buffer doesn't have a device resource instance, for now + CC_ASSERT(resource.get()); auto *const virtualResource = new ResourceEntry(name, static_cast(_virtualResources.size()), resource); return TypedHandle(create(virtualResource)); } diff --git a/native/cocos/renderer/frame-graph/PassInsertPointManager.cpp b/native/cocos/renderer/frame-graph/PassInsertPointManager.cpp index ae9d0acdd4..1e5f2e3ded 100644 --- a/native/cocos/renderer/frame-graph/PassInsertPointManager.cpp +++ b/native/cocos/renderer/frame-graph/PassInsertPointManager.cpp @@ -29,26 +29,26 @@ namespace cc { namespace framegraph { -PassInsertPointManager &PassInsertPointManager::getInstance() noexcept { +PassInsertPointManager &PassInsertPointManager::getInstance() { static PassInsertPointManager instance; return instance; } -PassInsertPoint PassInsertPointManager::record(const char *const name, const PassInsertPoint point) noexcept { +PassInsertPoint PassInsertPointManager::record(const char *const name, const PassInsertPoint point) { StringHandle nameHandle = _stringPool.find(name); if (nameHandle.isValid()) { CC_ASSERT(point == get(nameHandle)); return get(nameHandle); - } else { - nameHandle = _stringPool.stringToHandle(name); - CC_ASSERT(nameHandle == _insertPoints.size()); - _insertPoints.emplace_back(point); - return point; } + + nameHandle = _stringPool.stringToHandle(name); + CC_ASSERT(nameHandle == _insertPoints.size()); + _insertPoints.emplace_back(point); + return point; } -PassInsertPoint PassInsertPointManager::get(const char *const name) const noexcept { +PassInsertPoint PassInsertPointManager::get(const char *const name) const { const StringHandle nameHandle = _stringPool.find(name); CC_ASSERT(nameHandle.isValid()); return get(nameHandle); diff --git a/native/cocos/renderer/frame-graph/PassInsertPointManager.h b/native/cocos/renderer/frame-graph/PassInsertPointManager.h index b1bea73512..c448ea4c61 100644 --- a/native/cocos/renderer/frame-graph/PassInsertPointManager.h +++ b/native/cocos/renderer/frame-graph/PassInsertPointManager.h @@ -36,21 +36,21 @@ using PassInsertPoint = uint16_t; class PassInsertPointManager final { public: - PassInsertPointManager(const PassInsertPointManager &) = delete; - PassInsertPointManager(PassInsertPointManager &&) = delete; + PassInsertPointManager(const PassInsertPointManager &) = delete; + PassInsertPointManager(PassInsertPointManager &&) noexcept = delete; PassInsertPointManager &operator=(const PassInsertPointManager &) = delete; - PassInsertPointManager &operator=(PassInsertPointManager &&) = delete; + PassInsertPointManager &operator=(PassInsertPointManager &&) noexcept = delete; - static PassInsertPointManager &getInstance() noexcept; + static PassInsertPointManager &getInstance(); - PassInsertPoint record(const char *name, PassInsertPoint point) noexcept; - PassInsertPoint get(const char *name) const noexcept; + PassInsertPoint record(const char *name, PassInsertPoint point); + PassInsertPoint get(const char *name) const; private: PassInsertPointManager() = default; ~PassInsertPointManager() = default; - inline PassInsertPoint get(StringHandle name) const noexcept; + inline PassInsertPoint get(StringHandle name) const; StringPool _stringPool; std::vector _insertPoints{}; @@ -58,7 +58,7 @@ private: ////////////////////////////////////////////////////////////////////////// -PassInsertPoint PassInsertPointManager::get(const StringHandle name) const noexcept { +PassInsertPoint PassInsertPointManager::get(const StringHandle name) const { return _insertPoints[name]; } diff --git a/native/cocos/renderer/frame-graph/PassNode.cpp b/native/cocos/renderer/frame-graph/PassNode.cpp index 0b457bc130..5822302733 100644 --- a/native/cocos/renderer/frame-graph/PassNode.cpp +++ b/native/cocos/renderer/frame-graph/PassNode.cpp @@ -24,14 +24,14 @@ ****************************************************************************/ #include "PassNode.h" +#include #include "FrameGraph.h" #include "ResourceNode.h" -#include namespace cc { namespace framegraph { -PassNode::PassNode(const PassInsertPoint inserPoint, const StringHandle name, const ID &id, Executable *pass) noexcept +PassNode::PassNode(const PassInsertPoint inserPoint, const StringHandle name, const ID &id, Executable *pass) : _pass(pass), _name(name), _id(id), @@ -39,8 +39,7 @@ PassNode::PassNode(const PassInsertPoint inserPoint, const StringHandle name, co CC_ASSERT(_name.isValid()); } -Handle PassNode::read(FrameGraph &graph, const Handle &input) noexcept { - CC_ASSERT(check(graph, input, _writes)); +Handle PassNode::read(FrameGraph & /*graph*/, const Handle &input) { const auto it = std::find_if(_reads.begin(), _reads.end(), [input](const Handle handle) { return input == handle; }); @@ -52,8 +51,7 @@ Handle PassNode::read(FrameGraph &graph, const Handle &input) noexcept { return input; } -Handle PassNode::write(FrameGraph &graph, const Handle &output) noexcept { - CC_ASSERT(check(graph, output, _reads)); +Handle PassNode::write(FrameGraph &graph, const Handle &output) { CC_ASSERT(std::find_if(_writes.begin(), _writes.end(), [output](const Handle handle) { return output == handle; }) == _writes.end()); @@ -68,7 +66,7 @@ Handle PassNode::write(FrameGraph &graph, const Handle &output) noexcept { return handle; } -void PassNode::createRenderTargetAttachment(RenderTargetAttachment &&attachment) noexcept { +void PassNode::createRenderTargetAttachment(RenderTargetAttachment &&attachment) { if (attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { if (attachment.desc.slot == 0xff) { for (uint8_t i = 0; i < RenderTargetAttachment::DEPTH_STENCIL_SLOT_START; ++i) { @@ -98,7 +96,7 @@ void PassNode::createRenderTargetAttachment(RenderTargetAttachment &&attachment) _hasClearedAttachment = _hasClearedAttachment || (attachment.desc.loadOp == gfx::LoadOp::CLEAR); } -bool PassNode::canMerge(const FrameGraph &graph, const PassNode &passNode) const noexcept { +bool PassNode::canMerge(const FrameGraph &graph, const PassNode &passNode) const { const size_t attachmentCount = _attachments.size(); if (passNode._hasClearedAttachment || attachmentCount != passNode._attachments.size()) { @@ -123,7 +121,7 @@ bool PassNode::canMerge(const FrameGraph &graph, const PassNode &passNode) const return true; } -RenderTargetAttachment *PassNode::getRenderTargetAttachment(const Handle &handle) noexcept { +RenderTargetAttachment *PassNode::getRenderTargetAttachment(const Handle &handle) { const auto it = std::find_if(_attachments.begin(), _attachments.end(), [&handle](const RenderTargetAttachment &attachment) { return attachment.textureHandle == handle; }); @@ -131,7 +129,7 @@ RenderTargetAttachment *PassNode::getRenderTargetAttachment(const Handle &handle return it == _attachments.end() ? nullptr : &(*it); } -RenderTargetAttachment *PassNode::getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *const resource) noexcept { +RenderTargetAttachment *PassNode::getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *const resource) { const auto it = std::find_if(_attachments.begin(), _attachments.end(), [&](const RenderTargetAttachment &attachment) { return graph.getResourceNode(attachment.textureHandle).virtualResource == resource; }); @@ -139,56 +137,46 @@ RenderTargetAttachment *PassNode::getRenderTargetAttachment(const FrameGraph &gr return it == _attachments.end() ? nullptr : &(*it); } -void PassNode::requestTransientResources() noexcept { - std::for_each(_resourceRequestArray.begin(), _resourceRequestArray.end(), [](VirtualResource *const resource) { - if (!resource->isImported()) { - resource->request(); - } - }); +void PassNode::requestTransientResources() { + PassNode *it = this; - if (_next) { - _next->requestTransientResources(); - } + do { + std::for_each(it->_resourceRequestArray.begin(), it->_resourceRequestArray.end(), [](VirtualResource *const resource) { + if (!resource->isImported()) { + resource->request(); + } + }); + + it = it->_next; + } while (it); } -void PassNode::releaseTransientResources() noexcept { - std::for_each(_resourceReleaseArray.begin(), _resourceReleaseArray.end(), [](VirtualResource *const resource) { - if (!resource->isImported()) { - resource->release(); - } - }); +void PassNode::releaseTransientResources() { + PassNode *it = this; - if (_next) { - _next->releaseTransientResources(); - } + do { + // resources should be release in the reverse order to stabilize usages between frames + std::for_each(it->_resourceReleaseArray.rbegin(), it->_resourceReleaseArray.rend(), [](VirtualResource *const resource) { + if (!resource->isImported()) { + resource->release(); + } + }); + + it = it->_next; + } while (it); } -bool PassNode::check(FrameGraph &graph, const Handle &checkingHandle, std::vector const &handles) const noexcept { - // render target can not do both read & write - const VirtualResource *const inputResource = graph.getResourceNode(checkingHandle).virtualResource; - const auto it = std::find_if(handles.begin(), handles.end(), [&](Handle handle) { - return inputResource == graph.getResourceNode(handle).virtualResource; - }); +void PassNode::setDevicePassId(ID const id) { + PassNode *it = this; - if (it == handles.end()) { - return true; - } + do { + it->_devicePassId = id; - const Handle output = *it; - return std::find_if(_attachments.cbegin(), _attachments.cend(), [&output](const RenderTargetAttachment &attachment) { - return attachment.textureHandle == output; - }) == _attachments.end(); + it = it->_next; + } while (it); } -void PassNode::setDevicePassId(ID const id) noexcept { - _devicePassId = id; - - if (_next) { - _next->setDevicePassId(id); - } -} - -Handle PassNode::getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *const resource) const noexcept { +Handle PassNode::getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *const resource) const { const auto it = std::find_if(_writes.begin(), _writes.end(), [&](const Handle handle) { return graph.getResourceNode(handle).virtualResource == resource; }); diff --git a/native/cocos/renderer/frame-graph/PassNode.h b/native/cocos/renderer/frame-graph/PassNode.h index e184151e6c..7ac7acb8bc 100644 --- a/native/cocos/renderer/frame-graph/PassNode.h +++ b/native/cocos/renderer/frame-graph/PassNode.h @@ -40,29 +40,28 @@ class FrameGraph; class PassNode final { public: - PassNode(PassInsertPoint inserPoint, StringHandle name, const ID &id, Executable *pass) noexcept; + PassNode(PassInsertPoint inserPoint, StringHandle name, const ID &id, Executable *pass); ~PassNode() = default; PassNode(PassNode &&) noexcept = default; PassNode(const PassNode &) = delete; PassNode &operator=(const PassNode &) = delete; - PassNode &operator=(PassNode &&) = delete; + PassNode &operator=(PassNode &&) noexcept = delete; - Handle read(FrameGraph &graph, const Handle &input) noexcept; - Handle write(FrameGraph &graph, const Handle &output) noexcept; - void createRenderTargetAttachment(RenderTargetAttachment &&attachment) noexcept; - inline void sideEffect() noexcept; - inline void subpass(bool clearActionIgnoreable, bool end) noexcept; - inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept; + Handle read(FrameGraph &graph, const Handle &input); + Handle write(FrameGraph &graph, const Handle &output); + void createRenderTargetAttachment(RenderTargetAttachment &&attachment); + inline void sideEffect(); + inline void subpass(bool clearActionIgnoreable, bool end); + inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor); private: - bool canMerge(const FrameGraph &graph, const PassNode &passNode) const noexcept; - RenderTargetAttachment *getRenderTargetAttachment(const Handle &handle) noexcept; - RenderTargetAttachment *getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *resource) noexcept; - void requestTransientResources() noexcept; - void releaseTransientResources() noexcept; - bool check(FrameGraph &graph, const Handle &checkingHandle, std::vector const &handles) const noexcept; - void setDevicePassId(ID id) noexcept; - Handle getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *resource) const noexcept; + bool canMerge(const FrameGraph &graph, const PassNode &passNode) const; + RenderTargetAttachment *getRenderTargetAttachment(const Handle &handle); + RenderTargetAttachment *getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *resource); + void requestTransientResources(); + void releaseTransientResources(); + void setDevicePassId(ID id); + Handle getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *resource) const; std::unique_ptr _pass{nullptr}; std::vector _reads{}; @@ -96,17 +95,17 @@ private: ////////////////////////////////////////////////////////////////////////// -void PassNode::sideEffect() noexcept { +void PassNode::sideEffect() { _sideEffect = true; } -void PassNode::subpass(bool clearActionIgnoreable, bool end) noexcept { +void PassNode::subpass(bool clearActionIgnoreable, bool end) { _subpass = true; _clearActionIgnoreable = clearActionIgnoreable; _subpassEnd = end; } -void PassNode::setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept { +void PassNode::setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) { _customViewport = true; _viewport = viewport; _scissor = scissor; diff --git a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h index 0c9799140a..706adeee8c 100644 --- a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h +++ b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h @@ -67,6 +67,7 @@ struct RenderTargetAttachment final { uint8_t layer{0}; uint8_t index{0}; StoreOp storeOp{StoreOp::DISCARD}; + bool isGeneralLayout{false}; }; inline bool RenderTargetAttachment::Sorter::operator()(const RenderTargetAttachment &a1, const RenderTargetAttachment &a2) const noexcept { diff --git a/native/cocos/renderer/frame-graph/Resource.h b/native/cocos/renderer/frame-graph/Resource.h index 6534d67451..959f77399b 100644 --- a/native/cocos/renderer/frame-graph/Resource.h +++ b/native/cocos/renderer/frame-graph/Resource.h @@ -31,10 +31,8 @@ #include "renderer/gfx-base/GFXBuffer.h" #include "renderer/gfx-base/GFXDevice.h" #include "renderer/gfx-base/GFXFramebuffer.h" -#include "renderer/gfx-base/GFXGlobalBarrier.h" #include "renderer/gfx-base/GFXRenderPass.h" #include "renderer/gfx-base/GFXTexture.h" -#include "renderer/gfx-base/GFXTextureBarrier.h" namespace cc { namespace framegraph { @@ -72,16 +70,13 @@ public: Resource &operator=(const Resource &) = default; Resource &operator=(Resource &&) noexcept = default; - void createTransient() noexcept; - void createPersistent() noexcept; + void createTransient() noexcept; + void createPersistent() noexcept; - // temporary api. framegraph donot create _deviceObject, it come from window - void createPersistent(DeviceResourceType *external) noexcept; void destroyTransient() noexcept; void destroyPersistent() noexcept; inline DeviceResourceType *get() const noexcept; inline const Descriptor & getDesc() const noexcept; - DeviceResourceType *getDeviceObject() const { return _deviceObject; } private: void computeHash() noexcept; @@ -89,9 +84,6 @@ private: Descriptor _desc; DescriptorHash _hash{0}; DeviceResourceType *_deviceObject{nullptr}; - - // true : _deviceObject come form window, framegraph donot need to release it - bool _devcieObjectFromWindow = false; }; ////////////////////////////////////////////////////////////////////////// @@ -107,16 +99,6 @@ void Resource -void Resource::createPersistent(DeviceResourceType *external) noexcept { - computeHash(); - - if (!_deviceObject) { - _devcieObjectFromWindow = true; - _deviceObject = external; - } -} - template void Resource::createPersistent() noexcept { computeHash(); @@ -136,7 +118,7 @@ void Resource void Resource::destroyPersistent() noexcept { - if (_deviceObject && !_devcieObjectFromWindow) { + if (_deviceObject) { delete _deviceObject; _deviceObject = nullptr; } @@ -162,30 +144,27 @@ void Resource \ - struct ResourceDescriptorHasher final { \ - inline uint32_t operator()(const gfx::Type##Info &desc) const { \ - return gfx::Type::computeHash(desc); \ - } \ - }; \ - \ - template <> \ - struct DeviceResourceCreator final { \ - inline gfx::Type *operator()(const gfx::Type##Info &desc) const { \ - return gfx::Device::getInstance()->create##Type(desc); \ - } \ - }; \ - \ - using Type = Resource; /* NOLINT(bugprone-macro-parentheses) N/A */ \ +#define DEFINE_GFX_RESOURCE(Type) \ + template <> \ + struct ResourceDescriptorHasher final { \ + inline uint32_t operator()(const gfx::Type##Info &desc) const { \ + return gfx::Type::computeHash(desc); \ + } \ + }; \ + \ + template <> \ + struct DeviceResourceCreator final { \ + inline gfx::Type *operator()(const gfx::Type##Info &desc) const { \ + return gfx::Device::getInstance()->create##Type(desc); \ + } \ + }; \ + using Type = Resource; \ using Type##Handle = TypedHandle; DEFINE_GFX_RESOURCE(Buffer) DEFINE_GFX_RESOURCE(Framebuffer) -DEFINE_GFX_RESOURCE(GlobalBarrier) DEFINE_GFX_RESOURCE(RenderPass) DEFINE_GFX_RESOURCE(Texture) -DEFINE_GFX_RESOURCE(TextureBarrier) } // namespace framegraph } // namespace cc diff --git a/native/cocos/renderer/frame-graph/ResourceAllocator.h b/native/cocos/renderer/frame-graph/ResourceAllocator.h index 886e4d8883..5f957a16eb 100644 --- a/native/cocos/renderer/frame-graph/ResourceAllocator.h +++ b/native/cocos/renderer/frame-graph/ResourceAllocator.h @@ -153,13 +153,13 @@ void ResourceAllocator= j) { - destroyBegin = i - 1; + destroyBegin = i; } if (i >= destroyBegin) { @@ -167,7 +167,7 @@ void ResourceAllocator::value>> class ResourceEntry final : public VirtualResource { public: - explicit ResourceEntry(const StringHandle name, ID const id, const typename ResourceType::Descriptor &desc) noexcept; - ResourceEntry(const StringHandle name, ID const id, const ResourceType &resource) noexcept; - ResourceEntry() = delete; - ~ResourceEntry() = default; - ResourceEntry(const ResourceEntry &) = delete; - ResourceEntry(ResourceEntry &&) = delete; + explicit ResourceEntry(StringHandle name, ID id, const typename ResourceType::Descriptor &desc) noexcept; + ResourceEntry(StringHandle name, ID id, const ResourceType &resource) noexcept; + ResourceEntry() = delete; + ~ResourceEntry() override = default; + ResourceEntry(const ResourceEntry &) = delete; + ResourceEntry(ResourceEntry &&) noexcept = delete; ResourceEntry &operator=(const ResourceEntry &) = delete; - ResourceEntry &operator=(ResourceEntry &&) = delete; + ResourceEntry &operator=(ResourceEntry &&) noexcept = delete; void request() noexcept override; void release() noexcept override; diff --git a/native/cocos/renderer/frame-graph/ResourceNode.h b/native/cocos/renderer/frame-graph/ResourceNode.h index 8e68ccb3d1..3776de2b45 100644 --- a/native/cocos/renderer/frame-graph/ResourceNode.h +++ b/native/cocos/renderer/frame-graph/ResourceNode.h @@ -25,6 +25,8 @@ #pragma once +#include "VirtualResource.h" + namespace cc { namespace framegraph { diff --git a/native/cocos/renderer/frame-graph/VirtualResource.h b/native/cocos/renderer/frame-graph/VirtualResource.h index 3a9d3879ff..bdd4adb134 100644 --- a/native/cocos/renderer/frame-graph/VirtualResource.h +++ b/native/cocos/renderer/frame-graph/VirtualResource.h @@ -25,8 +25,8 @@ #pragma once -#include "renderer/gfx-base/GFXObject.h" #include "Handle.h" +#include "renderer/gfx-base/GFXObject.h" namespace cc { namespace framegraph { @@ -37,18 +37,18 @@ using ID = uint16_t; class VirtualResource { public: - VirtualResource(const StringHandle name, ID const id, bool const imported) noexcept; - VirtualResource() noexcept = delete; - virtual ~VirtualResource() = default; - VirtualResource(const VirtualResource &) = delete; - VirtualResource(VirtualResource &&) = delete; + VirtualResource(StringHandle name, ID id, bool imported) noexcept; + VirtualResource() noexcept = delete; + virtual ~VirtualResource() = default; + VirtualResource(const VirtualResource &) = delete; + VirtualResource(VirtualResource &&) noexcept = delete; VirtualResource &operator=(const VirtualResource &) = delete; - VirtualResource &operator=(VirtualResource &&) = delete; + VirtualResource &operator=(VirtualResource &&) noexcept = delete; virtual void request() noexcept = 0; virtual void release() noexcept = 0; bool isImported() const noexcept { return _imported; } - void updateLifetime(PassNode *const passNode) noexcept; + void updateLifetime(PassNode *passNode) noexcept; void newVersion() noexcept { ++_version; } virtual gfx::GFXObject *getDeviceResource() const noexcept = 0; diff --git a/native/cocos/renderer/gfx-agent/BufferAgent.cpp b/native/cocos/renderer/gfx-agent/BufferAgent.cpp index aa2f2fe8f4..e285331a1d 100644 --- a/native/cocos/renderer/gfx-agent/BufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/BufferAgent.cpp @@ -34,7 +34,7 @@ namespace gfx { BufferAgent::BufferAgent(Buffer *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } BufferAgent::~BufferAgent() { @@ -161,10 +161,9 @@ void BufferAgent::update(const void *buffer, uint size) { } void BufferAgent::getActorBuffer(const BufferAgent *buffer, MessageQueue *mq, uint size, uint8_t **pActorBuffer, bool *pNeedFreeing) { - uint frameIndex = DeviceAgent::getInstance()->getCurrentIndex(); - if (!buffer->_stagingBuffers.empty()) { // for frequent updates on big buffers - *pActorBuffer = buffer->_stagingBuffers[frameIndex]; + uint frameIndex = DeviceAgent::getInstance()->getCurrentIndex(); + *pActorBuffer = buffer->_stagingBuffers[frameIndex]; } else if (size > STAGING_BUFFER_THRESHOLD) { // less frequent updates on big buffers *pActorBuffer = reinterpret_cast(malloc(size)); *pNeedFreeing = true; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 25d170cd82..ce134d23e8 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -43,7 +43,7 @@ namespace gfx { CommandBufferAgent::CommandBufferAgent(CommandBuffer *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } void CommandBufferAgent::flushCommands(uint count, CommandBufferAgent *const *cmdBuffs, bool multiThreaded) { diff --git a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp index a495cbe944..3e5db285ea 100644 --- a/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DescriptorSetAgent.cpp @@ -30,7 +30,6 @@ #include "DescriptorSetAgent.h" #include "DescriptorSetLayoutAgent.h" #include "DeviceAgent.h" -#include "SamplerAgent.h" #include "TextureAgent.h" namespace cc { @@ -38,7 +37,7 @@ namespace gfx { DescriptorSetAgent::DescriptorSetAgent(DescriptorSet *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } DescriptorSetAgent::~DescriptorSetAgent() { @@ -128,7 +127,7 @@ void DescriptorSetAgent::bindSampler(uint binding, Sampler *sampler, uint index) DescriptorSetBindSampler, actor, getActor(), binding, binding, - sampler, static_cast(sampler)->getActor(), + sampler, sampler, index, index, { actor->bindSampler(binding, sampler, index); diff --git a/native/cocos/renderer/gfx-agent/DescriptorSetLayoutAgent.cpp b/native/cocos/renderer/gfx-agent/DescriptorSetLayoutAgent.cpp index 79d3b6eaa3..023ae952e2 100644 --- a/native/cocos/renderer/gfx-agent/DescriptorSetLayoutAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DescriptorSetLayoutAgent.cpp @@ -34,7 +34,7 @@ namespace gfx { DescriptorSetLayoutAgent::DescriptorSetLayoutAgent(DescriptorSetLayout *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } DescriptorSetLayoutAgent::~DescriptorSetLayoutAgent() { diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 0421554d5f..1ca78eeb4d 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -37,10 +37,12 @@ #include "PipelineStateAgent.h" #include "QueueAgent.h" #include "RenderPassAgent.h" -#include "SamplerAgent.h" #include "ShaderAgent.h" +#include "SwapchainAgent.h" #include "TextureAgent.h" #include "base/threading/ThreadSafeLinearAllocator.h" +#include "gfx-base/GFXDef-common.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { @@ -65,19 +67,18 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { return false; } - _context = _actor->getContext(); - _api = _actor->getGfxAPI(); - _deviceName = _actor->getDeviceName(); - _queue = CC_NEW(QueueAgent(_actor->getQueue())); - _cmdBuff = CC_NEW(CommandBufferAgent(_actor->getCommandBuffer())); - static_cast(_cmdBuff)->_queue = _queue; - _renderer = _actor->getRenderer(); - _vendor = _actor->getVendor(); - _caps = _actor->_caps; + _api = _actor->getGfxAPI(); + _deviceName = _actor->getDeviceName(); + _queue = CC_NEW(QueueAgent(_actor->getQueue())); + _cmdBuff = CC_NEW(CommandBufferAgent(_actor->getCommandBuffer())); + _renderer = _actor->getRenderer(); + _vendor = _actor->getVendor(); + _caps = _actor->_caps; memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); _mainMessageQueue = CC_NEW(MessageQueue); + static_cast(_cmdBuff)->_queue = _queue; static_cast(_cmdBuff)->initMessageQueue(); setMultithreaded(true); @@ -109,23 +110,19 @@ void DeviceAgent::doDestroy() { CC_SAFE_DELETE(_mainMessageQueue); } -void DeviceAgent::resize(uint width, uint height) { - ENQUEUE_MESSAGE_3( - _mainMessageQueue, DeviceResize, - actor, _actor, - width, width, - height, height, - { - actor->resize(width, height); - }); -} +void DeviceAgent::acquire(Swapchain *const *swapchains, uint32_t count) { + auto *actorSwapchains = _mainMessageQueue->allocate(count); + for (uint32_t i = 0; i < count; ++i) { + actorSwapchains[i] = static_cast(swapchains[i])->getActor(); + } -void DeviceAgent::acquire() { - ENQUEUE_MESSAGE_1( - _mainMessageQueue, DeviceAcquire, + ENQUEUE_MESSAGE_3( + _mainMessageQueue, DevicePresent, actor, _actor, + swapchains, actorSwapchains, + count, count, { - actor->acquire(); + actor->acquire(swapchains, count); }); } @@ -151,13 +148,13 @@ void DeviceAgent::setMultithreaded(bool multithreaded) { if (multithreaded) { _mainMessageQueue->setImmediateMode(false); - _actor->bindRenderContext(false); + _actor->bindContext(false); _mainMessageQueue->runConsumerThread(); ENQUEUE_MESSAGE_1( _mainMessageQueue, DeviceMakeCurrentTrue, actor, _actor, { - actor->bindDeviceContext(true); + actor->bindContext(true); CC_LOG_INFO("Device thread detached."); }); for (CommandBufferAgent *cmdBuff : _cmdBuffRefs) { @@ -168,11 +165,11 @@ void DeviceAgent::setMultithreaded(bool multithreaded) { _mainMessageQueue, DeviceMakeCurrentFalse, actor, _actor, { - actor->bindDeviceContext(false); + actor->bindContext(false); }); _mainMessageQueue->terminateConsumerThread(); _mainMessageQueue->setImmediateMode(true); - _actor->bindRenderContext(true); + _actor->bindContext(true); for (CommandBufferAgent *cmdBuff : _cmdBuffRefs) { cmdBuff->_messageQueue->setImmediateMode(true); } @@ -180,27 +177,6 @@ void DeviceAgent::setMultithreaded(bool multithreaded) { } } -void DeviceAgent::releaseSurface(uintptr_t windowHandle) { - ENQUEUE_MESSAGE_2( - _mainMessageQueue, DeviceReleaseSurface, - actor, _actor, - windowHandle, windowHandle, - { - actor->releaseSurface(windowHandle); - }); - _mainMessageQueue->kickAndWait(); -} - -void DeviceAgent::acquireSurface(uintptr_t windowHandle) { - ENQUEUE_MESSAGE_2( - _mainMessageQueue, DeviceAcquireSurface, - actor, _actor, - windowHandle, windowHandle, - { - actor->acquireSurface(windowHandle); - }); -} - CommandBuffer *DeviceAgent::createCommandBuffer(const CommandBufferInfo &info, bool /*hasAgent*/) { CommandBuffer *actor = _actor->createCommandBuffer(info, true); return CC_NEW(CommandBufferAgent(actor)); @@ -211,6 +187,11 @@ Queue *DeviceAgent::createQueue() { return CC_NEW(QueueAgent(actor)); } +Swapchain *DeviceAgent::createSwapchain() { + Swapchain *actor = _actor->createSwapchain(); + return CC_NEW(SwapchainAgent(actor)); +} + Buffer *DeviceAgent::createBuffer() { Buffer *actor = _actor->createBuffer(); return CC_NEW(BufferAgent(actor)); @@ -221,11 +202,6 @@ Texture *DeviceAgent::createTexture() { return CC_NEW(TextureAgent(actor)); } -Sampler *DeviceAgent::createSampler() { - Sampler *actor = _actor->createSampler(); - return CC_NEW(SamplerAgent(actor)); -} - Shader *DeviceAgent::createShader() { Shader *actor = _actor->createShader(); return CC_NEW(ShaderAgent(actor)); @@ -266,12 +242,16 @@ PipelineState *DeviceAgent::createPipelineState() { return CC_NEW(PipelineStateAgent(actor)); } -GlobalBarrier *DeviceAgent::createGlobalBarrier() { - return _actor->createGlobalBarrier(); +Sampler *DeviceAgent::createSampler(const SamplerInfo &info) { + return _actor->createSampler(info); } -TextureBarrier *DeviceAgent::createTextureBarrier() { - return _actor->createTextureBarrier(); +GlobalBarrier *DeviceAgent::createGlobalBarrier(const GlobalBarrierInfo &info) { + return _actor->createGlobalBarrier(info); +} + +TextureBarrier *DeviceAgent::createTextureBarrier(const TextureBarrierInfo &info) { + return _actor->createTextureBarrier(info); } void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { @@ -280,7 +260,7 @@ void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d bufferCount += regions[i].texSubres.layerCount; } uint totalSize = sizeof(BufferTextureCopy) * count + sizeof(uint8_t *) * bufferCount; - for (uint i = 0U, n = 0U; i < count; i++) { + for (uint i = 0U; i < count; i++) { const BufferTextureCopy ®ion = regions[i]; uint size = formatSize(dst->getFormat(), region.texExtent.width, region.texExtent.height, 1); @@ -330,6 +310,7 @@ void DeviceAgent::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buff { actor->copyTextureToBuffers(src, buffers, regions, count); }); + _mainMessageQueue->kickAndWait(); } diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index 9460e91e7d..0cc8c2dbfb 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -63,15 +63,14 @@ public: using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -80,18 +79,18 @@ public: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; - void flushCommands(CommandBuffer *const *cmdBuffs, uint count) override; - SurfaceTransform getSurfaceTransform() const override { return _actor->getSurfaceTransform(); } - uint getWidth() const override { return _actor->getWidth(); } - uint getHeight() const override { return _actor->getHeight(); } - MemoryStatus & getMemoryStatus() override { return _actor->getMemoryStatus(); } - uint getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } - uint getNumInstances() const override { return _actor->getNumInstances(); } - uint getNumTris() const override { return _actor->getNumTris(); } + + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; + + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + void flushCommands(CommandBuffer *const *cmdBuffs, uint count) override; + MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } + uint getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } + uint getNumInstances() const override { return _actor->getNumInstances(); } + uint getNumTris() const override { return _actor->getNumTris(); } uint getCurrentIndex() const { return _currentIndex; } void setMultithreaded(bool multithreaded); @@ -109,9 +108,6 @@ protected: bool doInit(const DeviceInfo &info) override; void doDestroy() override; - void releaseSurface(uintptr_t windowHandle) override; - void acquireSurface(uintptr_t windowHandle) override; - bool _multithreaded{false}; MessageQueue *_mainMessageQueue{nullptr}; diff --git a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp index 9d6c123619..21cd1f8e20 100644 --- a/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/FramebufferAgent.cpp @@ -36,7 +36,7 @@ namespace gfx { FramebufferAgent::FramebufferAgent(Framebuffer *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } FramebufferAgent::~FramebufferAgent() { diff --git a/native/cocos/renderer/gfx-agent/InputAssemblerAgent.cpp b/native/cocos/renderer/gfx-agent/InputAssemblerAgent.cpp index 4e6e9bd558..4d93e1e488 100644 --- a/native/cocos/renderer/gfx-agent/InputAssemblerAgent.cpp +++ b/native/cocos/renderer/gfx-agent/InputAssemblerAgent.cpp @@ -35,7 +35,7 @@ namespace gfx { InputAssemblerAgent::InputAssemblerAgent(InputAssembler *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } InputAssemblerAgent::~InputAssemblerAgent() { @@ -80,8 +80,8 @@ void InputAssemblerAgent::doDestroy() { }); } -void InputAssemblerAgent::setVertexCount(uint count) { - _vertexCount = count; +void InputAssemblerAgent::setVertexCount(uint32_t count) { + _drawInfo.vertexCount = count; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -91,8 +91,8 @@ void InputAssemblerAgent::setVertexCount(uint count) { }); } -void InputAssemblerAgent::setFirstVertex(uint first) { - _firstVertex = first; +void InputAssemblerAgent::setFirstVertex(uint32_t first) { + _drawInfo.firstVertex = first; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -102,8 +102,8 @@ void InputAssemblerAgent::setFirstVertex(uint first) { }); } -void InputAssemblerAgent::setIndexCount(uint count) { - _indexCount = count; +void InputAssemblerAgent::setIndexCount(uint32_t count) { + _drawInfo.indexCount = count; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -113,8 +113,8 @@ void InputAssemblerAgent::setIndexCount(uint count) { }); } -void InputAssemblerAgent::setFirstIndex(uint first) { - _firstIndex = first; +void InputAssemblerAgent::setFirstIndex(uint32_t first) { + _drawInfo.firstIndex = first; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -124,8 +124,8 @@ void InputAssemblerAgent::setFirstIndex(uint first) { }); } -void InputAssemblerAgent::setVertexOffset(uint offset) { - _vertexOffset = offset; +void InputAssemblerAgent::setVertexOffset(int32_t offset) { + _drawInfo.vertexOffset = offset; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -135,8 +135,8 @@ void InputAssemblerAgent::setVertexOffset(uint offset) { }); } -void InputAssemblerAgent::setInstanceCount(uint count) { - _instanceCount = count; +void InputAssemblerAgent::setInstanceCount(uint32_t count) { + _drawInfo.instanceCount = count; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), @@ -146,8 +146,8 @@ void InputAssemblerAgent::setInstanceCount(uint count) { }); } -void InputAssemblerAgent::setFirstInstance(uint first) { - _firstInstance = first; +void InputAssemblerAgent::setFirstInstance(uint32_t first) { + _drawInfo.firstInstance = first; ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), InputAssemblerDestroy, actor, getActor(), diff --git a/native/cocos/renderer/gfx-agent/InputAssemblerAgent.h b/native/cocos/renderer/gfx-agent/InputAssemblerAgent.h index 54bc0bf967..bae35762c1 100644 --- a/native/cocos/renderer/gfx-agent/InputAssemblerAgent.h +++ b/native/cocos/renderer/gfx-agent/InputAssemblerAgent.h @@ -36,13 +36,13 @@ public: explicit InputAssemblerAgent(InputAssembler *actor); ~InputAssemblerAgent() override; - void setVertexCount(uint count) override; - void setFirstVertex(uint first) override; - void setIndexCount(uint count) override; - void setFirstIndex(uint first) override; - void setVertexOffset(uint offset) override; - void setInstanceCount(uint count) override; - void setFirstInstance(uint first) override; + void setVertexCount(uint32_t count) override; + void setFirstVertex(uint32_t first) override; + void setIndexCount(uint32_t count) override; + void setFirstIndex(uint32_t first) override; + void setVertexOffset(int32_t offset) override; + void setInstanceCount(uint32_t count) override; + void setFirstInstance(uint32_t first) override; protected: void doInit(const InputAssemblerInfo &info) override; diff --git a/native/cocos/renderer/gfx-agent/PipelineLayoutAgent.cpp b/native/cocos/renderer/gfx-agent/PipelineLayoutAgent.cpp index ab0cf6334e..57c3fc3526 100644 --- a/native/cocos/renderer/gfx-agent/PipelineLayoutAgent.cpp +++ b/native/cocos/renderer/gfx-agent/PipelineLayoutAgent.cpp @@ -35,7 +35,7 @@ namespace gfx { PipelineLayoutAgent::PipelineLayoutAgent(PipelineLayout *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } PipelineLayoutAgent::~PipelineLayoutAgent() { diff --git a/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp b/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp index 1c0db809d3..d71680af7d 100644 --- a/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp +++ b/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp @@ -37,7 +37,7 @@ namespace gfx { PipelineStateAgent::PipelineStateAgent(PipelineState *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } PipelineStateAgent::~PipelineStateAgent() { diff --git a/native/cocos/renderer/gfx-agent/QueueAgent.cpp b/native/cocos/renderer/gfx-agent/QueueAgent.cpp index 0c0a142dab..5b8b40fe59 100644 --- a/native/cocos/renderer/gfx-agent/QueueAgent.cpp +++ b/native/cocos/renderer/gfx-agent/QueueAgent.cpp @@ -36,7 +36,7 @@ namespace gfx { QueueAgent::QueueAgent(Queue *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } QueueAgent::~QueueAgent() { diff --git a/native/cocos/renderer/gfx-agent/RenderPassAgent.cpp b/native/cocos/renderer/gfx-agent/RenderPassAgent.cpp index 4cd7674dd2..9cace3b941 100644 --- a/native/cocos/renderer/gfx-agent/RenderPassAgent.cpp +++ b/native/cocos/renderer/gfx-agent/RenderPassAgent.cpp @@ -34,7 +34,7 @@ namespace gfx { RenderPassAgent::RenderPassAgent(RenderPass *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } RenderPassAgent::~RenderPassAgent() { diff --git a/native/cocos/renderer/gfx-agent/SamplerAgent.cpp b/native/cocos/renderer/gfx-agent/SamplerAgent.cpp deleted file mode 100644 index b8205c45ab..0000000000 --- a/native/cocos/renderer/gfx-agent/SamplerAgent.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "base/CoreStd.h" -#include "base/threading/MessageQueue.h" - -#include "DescriptorSetLayoutAgent.h" -#include "DeviceAgent.h" -#include "SamplerAgent.h" - -namespace cc { -namespace gfx { - -SamplerAgent::SamplerAgent(Sampler *actor) -: Agent(actor) { - _typedID = generateObjectID(); -} - -SamplerAgent::~SamplerAgent() { - ENQUEUE_MESSAGE_1( - DeviceAgent::getInstance()->getMessageQueue(), - SamplerDestruct, - actor, _actor, - { - CC_SAFE_DELETE(actor); - }); -} - -void SamplerAgent::doInit(const SamplerInfo &info) { - ENQUEUE_MESSAGE_2( - DeviceAgent::getInstance()->getMessageQueue(), - SamplerInit, - actor, getActor(), - info, info, - { - actor->initialize(info); - }); -} - -void SamplerAgent::doDestroy() { - ENQUEUE_MESSAGE_1( - DeviceAgent::getInstance()->getMessageQueue(), - SamplerDestroy, - actor, getActor(), - { - actor->destroy(); - }); -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-agent/ShaderAgent.cpp b/native/cocos/renderer/gfx-agent/ShaderAgent.cpp index f64fad9faf..682072d3b4 100644 --- a/native/cocos/renderer/gfx-agent/ShaderAgent.cpp +++ b/native/cocos/renderer/gfx-agent/ShaderAgent.cpp @@ -34,7 +34,7 @@ namespace gfx { ShaderAgent::ShaderAgent(Shader *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } ShaderAgent::~ShaderAgent() { diff --git a/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp b/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp new file mode 100644 index 0000000000..4ede4d5faa --- /dev/null +++ b/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp @@ -0,0 +1,127 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "base/CoreStd.h" +#include "base/threading/MessageQueue.h" + +#include "DeviceAgent.h" +#include "SwapchainAgent.h" +#include "gfx-agent/TextureAgent.h" + +namespace cc { +namespace gfx { + +SwapchainAgent::SwapchainAgent(Swapchain *actor) +: Agent(actor) { + _typedID = actor->getTypedID(); +} + +SwapchainAgent::~SwapchainAgent() { + CC_SAFE_DELETE(_depthStencilTexture); + CC_SAFE_DELETE(_colorTexture); + + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), SwapchainDestruct, + actor, _actor, + { + CC_SAFE_DELETE(actor); + }); +} + +void SwapchainAgent::doInit(const SwapchainInfo &info) { + ENQUEUE_MESSAGE_2( + DeviceAgent::getInstance()->getMessageQueue(), SwapchainInit, + actor, getActor(), + info, info, + { + actor->initialize(info); + }); + + DeviceAgent::getInstance()->getMessageQueue()->kickAndWait(); + + auto *colorTexture = CC_NEW(TextureAgent(_actor->getColorTexture())); + colorTexture->renounceOwnership(); + _colorTexture = colorTexture; + + auto *depthStencilTexture = CC_NEW(TextureAgent(_actor->getDepthStencilTexture())); + depthStencilTexture->renounceOwnership(); + _depthStencilTexture = depthStencilTexture; + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = _actor->getColorTexture()->getFormat(); + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = _actor->getDepthStencilTexture()->getFormat(); + initTexture(textureInfo, _depthStencilTexture); +} + +void SwapchainAgent::doDestroy() { + CC_SAFE_DELETE(_depthStencilTexture); + CC_SAFE_DELETE(_colorTexture); + + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), SwapchainDestroy, + actor, getActor(), + { + actor->destroy(); + }); +} + +void SwapchainAgent::doResize(uint32_t width, uint32_t height, SurfaceTransform transform) { + ENQUEUE_MESSAGE_4( + DeviceAgent::getInstance()->getMessageQueue(), SwapchainResize, + actor, getActor(), + width, width, + height, height, + transform, transform, + { + actor->resize(width, height, transform); + }); +} + +void SwapchainAgent::doDestroySurface() { + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), SwapchaindestroySurface, + actor, getActor(), + { + actor->destroySurface(); + }); +} + +void SwapchainAgent::doCreateSurface(void *windowHandle) { + ENQUEUE_MESSAGE_2( + DeviceAgent::getInstance()->getMessageQueue(), SwapchaincreateSurface, + actor, getActor(), + windowHandle, windowHandle, + { + actor->createSurface(windowHandle); + }); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-validator/SamplerValidator.h b/native/cocos/renderer/gfx-agent/SwapchainAgent.h similarity index 75% rename from native/cocos/renderer/gfx-validator/SamplerValidator.h rename to native/cocos/renderer/gfx-agent/SwapchainAgent.h index 793208e769..02291a85ce 100644 --- a/native/cocos/renderer/gfx-validator/SamplerValidator.h +++ b/native/cocos/renderer/gfx-agent/SwapchainAgent.h @@ -26,19 +26,24 @@ #pragma once #include "base/Agent.h" -#include "gfx-base/GFXSampler.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { -class CC_DLL SamplerValidator final : public Agent { +class CC_DLL SwapchainAgent final : public Agent { public: - explicit SamplerValidator(Sampler *actor); - ~SamplerValidator() override; + explicit SwapchainAgent(Swapchain *actor); + ~SwapchainAgent() override; + + bool isPreRotationEnabled() override { return _actor->isPreRotationEnabled(); } protected: - void doInit(const SamplerInfo &info) override; + void doInit(const SwapchainInfo &info) override; void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-agent/TextureAgent.cpp b/native/cocos/renderer/gfx-agent/TextureAgent.cpp index 86b5428f2a..41c951a661 100644 --- a/native/cocos/renderer/gfx-agent/TextureAgent.cpp +++ b/native/cocos/renderer/gfx-agent/TextureAgent.cpp @@ -28,23 +28,27 @@ #include "DeviceAgent.h" #include "TextureAgent.h" +#include "gfx-agent/SwapchainAgent.h" +#include "gfx-base/GFXDef.h" namespace cc { namespace gfx { TextureAgent::TextureAgent(Texture *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } TextureAgent::~TextureAgent() { - ENQUEUE_MESSAGE_1( - DeviceAgent::getInstance()->getMessageQueue(), - TextureDestruct, - actor, _actor, - { - CC_SAFE_DELETE(actor); - }); + if (_ownTheActor) { + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), + TextureDestruct, + actor, _actor, + { + CC_SAFE_DELETE(actor); + }); + } } void TextureAgent::doInit(const TextureInfo &info) { @@ -72,6 +76,10 @@ void TextureAgent::doInit(const TextureViewInfo &info) { }); } +void TextureAgent::doInit(const SwapchainTextureInfo &info) { + // the actor is already initialized +} + void TextureAgent::doDestroy() { ENQUEUE_MESSAGE_1( DeviceAgent::getInstance()->getMessageQueue(), diff --git a/native/cocos/renderer/gfx-agent/TextureAgent.h b/native/cocos/renderer/gfx-agent/TextureAgent.h index caf2ff4d05..4a2501607f 100644 --- a/native/cocos/renderer/gfx-agent/TextureAgent.h +++ b/native/cocos/renderer/gfx-agent/TextureAgent.h @@ -31,16 +31,21 @@ namespace cc { namespace gfx { -class CC_DLL TextureAgent final : public Agent { +class CC_DLL TextureAgent : public Agent { public: explicit TextureAgent(Texture *actor); ~TextureAgent() override; + inline void renounceOwnership() { _ownTheActor = false; } + protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; + void doInit(const SwapchainTextureInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; + + bool _ownTheActor = true; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXBase.h b/native/cocos/renderer/gfx-base/GFXBase.h index 794be08aa9..83ec8c944e 100644 --- a/native/cocos/renderer/gfx-base/GFXBase.h +++ b/native/cocos/renderer/gfx-base/GFXBase.h @@ -27,18 +27,18 @@ #include "GFXBuffer.h" #include "GFXCommandBuffer.h" -#include "GFXContext.h" #include "GFXDescriptorSet.h" #include "GFXDescriptorSetLayout.h" #include "GFXDevice.h" #include "GFXFramebuffer.h" -#include "GFXGlobalBarrier.h" #include "GFXInputAssembler.h" #include "GFXPipelineLayout.h" #include "GFXPipelineState.h" #include "GFXQueue.h" #include "GFXRenderPass.h" -#include "GFXSampler.h" #include "GFXShader.h" +#include "GFXSwapchain.h" #include "GFXTexture.h" -#include "GFXTextureBarrier.h" +#include "states/GFXGlobalBarrier.h" +#include "states/GFXSampler.h" +#include "states/GFXTextureBarrier.h" diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index 9eeedf854d..477beb420e 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -88,11 +88,6 @@ public: inline void pipelineBarrier(const GlobalBarrier *barrier); inline void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrierList &textureBarriers, const TextureList &textures); - inline void bindDescriptorSetForJS(uint set, DescriptorSet *descriptorSet); - inline void bindDescriptorSetForJS(uint set, DescriptorSet *descriptorSet, const vector &dynamicOffsets); - inline void beginRenderPassForJS(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint stencil, const CommandBufferList &secondaryCBs); - inline void beginRenderPassForJS(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint stencil); - inline Queue * getQueue() const { return _queue; } inline CommandBufferType getType() const { return _type; } @@ -155,9 +150,7 @@ void CommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, co } void CommandBuffer::draw(InputAssembler *ia) { - DrawInfo info; - ia->extractDrawInfo(info); - draw(info); + draw(ia->getDrawInfo()); } void CommandBuffer::copyBuffersToTexture(const BufferDataList &buffers, Texture *texture, const BufferTextureCopyList ®ions) { @@ -176,21 +169,5 @@ void CommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const TextureB pipelineBarrier(barrier, textureBarriers.data(), textures.data(), utils::toUint(textureBarriers.size())); } -void CommandBuffer::bindDescriptorSetForJS(uint set, DescriptorSet *descriptorSet) { - bindDescriptorSet(set, descriptorSet, 0, nullptr); -} - -void CommandBuffer::bindDescriptorSetForJS(uint set, DescriptorSet *descriptorSet, const vector &dynamicOffsets) { - bindDescriptorSet(set, descriptorSet, utils::toUint(dynamicOffsets.size()), dynamicOffsets.data()); -} - -void CommandBuffer::beginRenderPassForJS(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint stencil, const CommandBufferList &secondaryCBs) { - beginRenderPass(renderPass, fbo, renderArea, colors.data(), depth, stencil, secondaryCBs.data(), utils::toUint(secondaryCBs.size())); -} - -void CommandBuffer::beginRenderPassForJS(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const ColorList &colors, float depth, uint stencil) { - beginRenderPass(renderPass, fbo, renderArea, colors.data(), depth, stencil, nullptr, 0); -} - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXContext.h b/native/cocos/renderer/gfx-base/GFXContext.h deleted file mode 100644 index 7235a95291..0000000000 --- a/native/cocos/renderer/gfx-base/GFXContext.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "GFXObject.h" - -namespace cc { -namespace gfx { - -class CC_DLL Context : public Object { -public: - Context(); - ~Context() override; - - bool initialize(const ContextInfo &info); - void destroy(); - - virtual void present() = 0; - - inline Context * getSharedContext() const { return _sharedContext; } - inline VsyncMode getVsyncMode() const { return _vsyncMode; } - inline Format getColorFormat() const { return _colorFmt; } - inline Format getDepthStencilFormat() const { return _depthStencilFmt; } - -protected: - virtual bool doInit(const ContextInfo &info) = 0; - virtual void doDestroy() = 0; - - uintptr_t _windowHandle = 0; - Context * _sharedContext = nullptr; - VsyncMode _vsyncMode = VsyncMode::OFF; - Format _colorFmt = Format::UNKNOWN; - Format _depthStencilFmt = Format::UNKNOWN; -}; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 81ad50df8f..e5ccce7298 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -39,7 +39,6 @@ * * native-specific structs should not be included here, put them in GFXDef.h instead * * no typedefs, only usings * * define struct members first, then other helper functions - * * macros are hardcoded in the generator for now * * aliases can only be used as types, not values (e.g. BufferUsage::NONE is illegal) * * parser directives can be specified in comments right after struct member declarations: * * @ts-nullable: declare the member optional @@ -52,6 +51,7 @@ namespace gfx { class GFXObject; class Device; +class Swapchain; class Buffer; class GlobalBarrier; class TextureBarrier; @@ -74,17 +74,18 @@ using TextureBarrierList = vector; using BufferDataList = vector; using CommandBufferList = vector; -constexpr uint MAX_ATTACHMENTS = 4U; -constexpr uint INVALID_BINDING = static_cast(-1); -constexpr uint SUBPASS_EXTERNAL = static_cast(-1); +constexpr uint32_t MAX_ATTACHMENTS = 4U; +constexpr uint32_t INVALID_BINDING = ~0U; +constexpr uint32_t SUBPASS_EXTERNAL = ~0U; using BufferList = vector; using TextureList = vector; using SamplerList = vector; using DescriptorSetLayoutList = vector; -enum class ObjectType { +enum class ObjectType : uint32_t { UNKNOWN, + SWAPCHAIN, BUFFER, TEXTURE, RENDER_PASS, @@ -101,17 +102,18 @@ enum class ObjectType { GLOBAL_BARRIER, TEXTURE_BARRIER, BUFFER_BARRIER, + COUNT, }; CC_ENUM_CONVERSION_OPERATOR(ObjectType); -enum class Status { +enum class Status : uint32_t { UNREADY, FAILED, SUCCESS, }; CC_ENUM_CONVERSION_OPERATOR(Status); -enum class API { +enum class API : uint32_t { UNKNOWN, GLES2, GLES3, @@ -123,7 +125,7 @@ enum class API { }; CC_ENUM_CONVERSION_OPERATOR(API); -enum class SurfaceTransform { +enum class SurfaceTransform : uint32_t { IDENTITY, ROTATE_90, ROTATE_180, @@ -131,7 +133,7 @@ enum class SurfaceTransform { }; CC_ENUM_CONVERSION_OPERATOR(SurfaceTransform); -enum class Feature { +enum class Feature : uint32_t { COLOR_FLOAT, COLOR_HALF_FLOAT, TEXTURE_FLOAT, @@ -155,7 +157,7 @@ enum class Feature { }; CC_ENUM_CONVERSION_OPERATOR(Feature); -enum class Format { +enum class Format : uint32_t { UNKNOWN, @@ -220,12 +222,8 @@ enum class Format { RGB9E5, // Depth-Stencil Format - D16, - D16S8, - D24, - D24S8, - D32F, - D32F_S8, + DEPTH, + DEPTH_STENCIL, // Compressed Format @@ -314,7 +312,7 @@ enum class Format { }; CC_ENUM_CONVERSION_OPERATOR(Format); -enum class FormatType { +enum class FormatType : uint32_t { NONE, UNORM, SNORM, @@ -325,7 +323,7 @@ enum class FormatType { }; CC_ENUM_CONVERSION_OPERATOR(FormatType); -enum class Type { +enum class Type : uint32_t { UNKNOWN, BOOL, BOOL2, @@ -385,7 +383,7 @@ bool isCombinedImageSampler(Type type); bool isSampledImage(Type type); bool isStorageImage(Type type); -enum class BufferUsageBit : FlagBits { +enum class BufferUsageBit : uint32_t { NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, @@ -398,30 +396,30 @@ enum class BufferUsageBit : FlagBits { using BufferUsage = BufferUsageBit; CC_ENUM_BITWISE_OPERATORS(BufferUsageBit); -enum class BufferFlagBit : FlagBits { +enum class BufferFlagBit : uint32_t { NONE = 0, }; using BufferFlags = BufferFlagBit; CC_ENUM_BITWISE_OPERATORS(BufferFlagBit); -enum class MemoryAccessBit : FlagBits { +enum class MemoryAccessBit : uint32_t { NONE = 0, READ_ONLY = 0x1, WRITE_ONLY = 0x2, READ_WRITE = READ_ONLY | WRITE_ONLY, }; using MemoryAccess = MemoryAccessBit; -CC_ENUM_CONVERSION_OPERATOR(MemoryAccessBit); +CC_ENUM_BITWISE_OPERATORS(MemoryAccessBit); -enum class MemoryUsageBit : FlagBits { +enum class MemoryUsageBit : uint32_t { NONE = 0, - DEVICE = 0x1, - HOST = 0x2, + DEVICE = 0x1, // for rarely-updated resources, use MemoryUsageBit::DEVICE + HOST = 0x2, // for frequently-updated resources, use MemoryUsageBit::DEVICE | MemoryUsageBit::HOST }; using MemoryUsage = MemoryUsageBit; CC_ENUM_BITWISE_OPERATORS(MemoryUsageBit); -enum class TextureType { +enum class TextureType : uint32_t { TEX1D, TEX2D, TEX3D, @@ -431,7 +429,7 @@ enum class TextureType { }; CC_ENUM_CONVERSION_OPERATOR(TextureType); -enum class TextureUsageBit : FlagBits { +enum class TextureUsageBit : uint32_t { NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, @@ -444,27 +442,49 @@ enum class TextureUsageBit : FlagBits { using TextureUsage = TextureUsageBit; CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); -enum class TextureFlagBit : FlagBits { +enum class TextureFlagBit : uint32_t { NONE = 0, - GEN_MIPMAP = 0x1, - IMMUTABLE = 0x2, - GENERAL_LAYOUT = 0x4, + GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter + RESIZABLE = 0x2, // Make the texture resizable, should be avoided whenever possible + GENERAL_LAYOUT = 0x4, // For inout framebuffer attachments }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); -enum class SampleCount { - X1 = 0x1, - X2 = 0x2, - X4 = 0x4, - X8 = 0x8, - X16 = 0x10, - X32 = 0x20, - X64 = 0x40, +enum class SampleCount : uint32_t { + ONE, // Single sample + MULTIPLE_PERFORMANCE, // Multiple samples prioritizing performance over quality + MULTIPLE_BALANCE, // Multiple samples leveraging both quality and performance + MULTIPLE_QUALITY, // Multiple samples prioritizing quality over performance }; CC_ENUM_CONVERSION_OPERATOR(SampleCount); -enum class Filter { +enum class VsyncMode : uint32_t { + // The application does not synchronizes with the vertical sync. + // If application renders faster than the display refreshes, frames are wasted and tearing may be observed. + // FPS is uncapped. Maximum power consumption. If unsupported, "ON" value will be used instead. Minimum latency. + OFF, + // The application is always synchronized with the vertical sync. Tearing does not happen. + // FPS is capped to the display's refresh rate. For fast applications, battery life is improved. Always supported. + ON, + // The application synchronizes with the vertical sync, but only if the application rendering speed is greater than refresh rate. + // Compared to OFF, there is no tearing. Compared to ON, the FPS will be improved for "slower" applications. + // If unsupported, "ON" value will be used instead. Recommended for most applications. Default if supported. + RELAXED, + // The presentation engine will always use the latest fully rendered image. + // Compared to OFF, no tearing will be observed. + // Compared to ON, battery power will be worse, especially for faster applications. + // If unsupported, "OFF" will be attempted next. + MAILBOX, + // The application is capped to using half the vertical sync time. + // FPS artificially capped to Half the display speed (usually 30fps) to maintain battery. + // Best possible battery savings. Worst possible performance. + // Recommended for specific applications where battery saving is critical. + HALF, +}; +CC_ENUM_CONVERSION_OPERATOR(VsyncMode); + +enum class Filter : uint32_t { NONE, POINT, LINEAR, @@ -472,7 +492,7 @@ enum class Filter { }; CC_ENUM_CONVERSION_OPERATOR(Filter); -enum class Address { +enum class Address : uint32_t { WRAP, MIRROR, CLAMP, @@ -480,7 +500,7 @@ enum class Address { }; CC_ENUM_CONVERSION_OPERATOR(Address); -enum class ComparisonFunc { +enum class ComparisonFunc : uint32_t { NEVER, LESS, EQUAL, @@ -492,7 +512,7 @@ enum class ComparisonFunc { }; CC_ENUM_CONVERSION_OPERATOR(ComparisonFunc); -enum class StencilOp { +enum class StencilOp : uint32_t { ZERO, KEEP, REPLACE, @@ -504,7 +524,7 @@ enum class StencilOp { }; CC_ENUM_CONVERSION_OPERATOR(StencilOp); -enum class BlendFactor { +enum class BlendFactor : uint32_t { ZERO, ONE, SRC_ALPHA, @@ -523,7 +543,7 @@ enum class BlendFactor { }; CC_ENUM_CONVERSION_OPERATOR(BlendFactor); -enum class BlendOp { +enum class BlendOp : uint32_t { ADD, SUB, REV_SUB, @@ -532,7 +552,7 @@ enum class BlendOp { }; CC_ENUM_CONVERSION_OPERATOR(BlendOp); -enum class ColorMask : FlagBits { +enum class ColorMask : uint32_t { NONE = 0x0, R = 0x1, G = 0x2, @@ -542,7 +562,7 @@ enum class ColorMask : FlagBits { }; CC_ENUM_BITWISE_OPERATORS(ColorMask); -enum class ShaderStageFlagBit : FlagBits { +enum class ShaderStageFlagBit : uint32_t { NONE = 0x0, VERTEX = 0x1, CONTROL = 0x2, @@ -555,20 +575,20 @@ enum class ShaderStageFlagBit : FlagBits { using ShaderStageFlags = ShaderStageFlagBit; CC_ENUM_BITWISE_OPERATORS(ShaderStageFlagBit); -enum class LoadOp { +enum class LoadOp : uint32_t { LOAD, // Load the contents from the fbo from previous CLEAR, // Clear the fbo DISCARD, // Ignore writing to the fbo and keep old data }; CC_ENUM_CONVERSION_OPERATOR(LoadOp); -enum class StoreOp { +enum class StoreOp : uint32_t { STORE, // Write the source to the destination DISCARD, // Don't write the source to the destination }; CC_ENUM_CONVERSION_OPERATOR(StoreOp); -enum class AccessType { +enum class AccessType : uint32_t { NONE, // Read access @@ -606,7 +626,7 @@ CC_ENUM_CONVERSION_OPERATOR(AccessType); using AccessTypeList = std::vector; -enum class ResolveMode { +enum class ResolveMode : uint32_t { NONE, SAMPLE_ZERO, AVERAGE, @@ -615,14 +635,14 @@ enum class ResolveMode { }; CC_ENUM_CONVERSION_OPERATOR(ResolveMode); -enum class PipelineBindPoint { +enum class PipelineBindPoint : uint32_t { GRAPHICS, COMPUTE, RAY_TRACING, }; CC_ENUM_CONVERSION_OPERATOR(PipelineBindPoint); -enum class PrimitiveMode { +enum class PrimitiveMode : uint32_t { POINT_LIST, LINE_LIST, LINE_STRIP, @@ -641,27 +661,27 @@ enum class PrimitiveMode { }; CC_ENUM_CONVERSION_OPERATOR(PrimitiveMode); -enum class PolygonMode { +enum class PolygonMode : uint32_t { FILL, POINT, LINE, }; CC_ENUM_CONVERSION_OPERATOR(PolygonMode); -enum class ShadeModel { +enum class ShadeModel : uint32_t { GOURAND, FLAT, }; CC_ENUM_CONVERSION_OPERATOR(ShadeModel); -enum class CullMode { +enum class CullMode : uint32_t { NONE, FRONT, BACK, }; CC_ENUM_CONVERSION_OPERATOR(CullMode); -enum class DynamicStateFlagBit : FlagBits { +enum class DynamicStateFlagBit : uint32_t { NONE = 0x0, VIEWPORT = 0x1, SCISSOR = 0x2, @@ -677,14 +697,14 @@ CC_ENUM_BITWISE_OPERATORS(DynamicStateFlagBit); using DynamicStateList = vector; -enum class StencilFace { +enum class StencilFace : uint32_t { FRONT = 0x1, BACK = 0x2, ALL = 0x3, }; CC_ENUM_BITWISE_OPERATORS(StencilFace); -enum class DescriptorType : FlagBits { +enum class DescriptorType : uint32_t { UNKNOWN = 0, UNIFORM_BUFFER = 0x1, DYNAMIC_UNIFORM_BUFFER = 0x2, @@ -698,20 +718,20 @@ enum class DescriptorType : FlagBits { }; CC_ENUM_BITWISE_OPERATORS(DescriptorType); -enum class QueueType { +enum class QueueType : uint32_t { GRAPHICS, COMPUTE, TRANSFER, }; CC_ENUM_CONVERSION_OPERATOR(QueueType); -enum class CommandBufferType { +enum class CommandBufferType : uint32_t { PRIMARY, SECONDARY, }; CC_ENUM_CONVERSION_OPERATOR(CommandBufferType); -enum class ClearFlagBit : FlagBits { +enum class ClearFlagBit : uint32_t { NONE = 0, COLOR = 0x1, DEPTH = 0x2, @@ -723,50 +743,48 @@ using ClearFlags = ClearFlagBit; CC_ENUM_BITWISE_OPERATORS(ClearFlagBit); struct Size { - uint x = 0U; - uint y = 0U; - uint z = 0U; + uint32_t x{0U}; + uint32_t y{0U}; + uint32_t z{0U}; }; struct DeviceCaps { - uint maxVertexAttributes = 0U; - uint maxVertexUniformVectors = 0U; - uint maxFragmentUniformVectors = 0U; - uint maxTextureUnits = 0U; - uint maxImageUnits = 0U; - uint maxVertexTextureUnits = 0U; - uint maxColorRenderTargets = 0U; - uint maxShaderStorageBufferBindings = 0U; - uint maxShaderStorageBlockSize = 0U; - uint maxUniformBufferBindings = 0U; - uint maxUniformBlockSize = 0U; - uint maxTextureSize = 0U; - uint maxCubeMapTextureSize = 0U; - uint depthBits = 0U; - uint stencilBits = 0U; - uint uboOffsetAlignment = 1U; + uint32_t maxVertexAttributes{0U}; + uint32_t maxVertexUniformVectors{0U}; + uint32_t maxFragmentUniformVectors{0U}; + uint32_t maxTextureUnits{0U}; + uint32_t maxImageUnits{0U}; + uint32_t maxVertexTextureUnits{0U}; + uint32_t maxColorRenderTargets{0U}; + uint32_t maxShaderStorageBufferBindings{0U}; + uint32_t maxShaderStorageBlockSize{0U}; + uint32_t maxUniformBufferBindings{0U}; + uint32_t maxUniformBlockSize{0U}; + uint32_t maxTextureSize{0U}; + uint32_t maxCubeMapTextureSize{0U}; + uint32_t uboOffsetAlignment{1U}; - uint maxComputeSharedMemorySize = 0U; - uint maxComputeWorkGroupInvocations = 0U; - Size maxComputeWorkGroupSize; - Size maxComputeWorkGroupCount; + uint32_t maxComputeSharedMemorySize{0U}; + uint32_t maxComputeWorkGroupInvocations{0U}; + Size maxComputeWorkGroupSize; + Size maxComputeWorkGroupCount; - float clipSpaceMinZ = -1.0F; - float screenSpaceSignY = 1.0F; - float clipSpaceSignY = 1.0F; + float clipSpaceMinZ{-1.F}; + float screenSpaceSignY{1.F}; + float clipSpaceSignY{1.F}; }; struct Offset { - int x = 0; - int y = 0; - int z = 0; + int32_t x{0}; + int32_t y{0}; + int32_t z{0}; }; struct Rect { - int x = 0; - int y = 0; - uint width = 0U; - uint height = 0U; + int32_t x{0}; + int32_t y{0}; + uint32_t width{0U}; + uint32_t height{0U}; bool operator==(const Rect &rs) const { return x == rs.x && @@ -781,22 +799,22 @@ struct Rect { }; struct Extent { - uint width = 0U; - uint height = 0U; - uint depth = 1U; + uint32_t width{0U}; + uint32_t height{0U}; + uint32_t depth{1U}; }; struct TextureSubresLayers { - uint mipLevel = 0U; - uint baseArrayLayer = 0U; - uint layerCount = 1U; + uint32_t mipLevel{0U}; + uint32_t baseArrayLayer{0U}; + uint32_t layerCount{1U}; }; struct TextureSubresRange { - uint baseMipLevel = 0U; - uint levelCount = 1U; - uint baseArrayLayer = 0U; - uint layerCount = 1U; + uint32_t baseMipLevel{0U}; + uint32_t levelCount{1U}; + uint32_t baseArrayLayer{0U}; + uint32_t layerCount{1U}; }; struct TextureCopy { @@ -818,8 +836,8 @@ struct TextureBlit { using TextureBlitList = vector; struct BufferTextureCopy { - uint buffStride = 0; - uint buffTexHeight = 0; + uint32_t buffStride{0U}; + uint32_t buffTexHeight{0U}; Offset texOffset; Extent texExtent; TextureSubresLayers texSubres; @@ -827,12 +845,12 @@ struct BufferTextureCopy { using BufferTextureCopyList = vector; struct Viewport { - int left = 0; - int top = 0; - uint width = 0; - uint height = 0; - float minDepth = 0.0F; - float maxDepth = 1.0F; + int32_t left{0}; + int32_t top{0}; + uint32_t width{0U}; + uint32_t height{0U}; + float minDepth{0.F}; + float maxDepth{1.F}; bool operator==(const Viewport &rs) const { return (left == rs.left && @@ -849,10 +867,10 @@ struct Viewport { }; struct Color { - float x = 0.0F; - float y = 0.0F; - float z = 0.0F; - float w = 0.0F; + float x{0.F}; + float y{0.F}; + float z{0.F}; + float w{0.F}; bool operator==(const Color &rhs) const { return (math::IsEqualF(x, rhs.x) && @@ -875,44 +893,56 @@ using ColorList = vector; * offsets for each descriptor type in each set. */ struct BindingMappingInfo { - std::vector bufferOffsets; - std::vector samplerOffsets; - uint flexibleSet = 0U; + std::vector bufferOffsets; + std::vector samplerOffsets; + uint32_t flexibleSet{0U}; +}; + +struct SwapchainInfo { + void * windowHandle{nullptr}; // @ts-overrides { type: 'HTMLCanvasElement' } + VsyncMode vsyncMode{VsyncMode::ON}; + + uint32_t width{0U}; + uint32_t height{0U}; +}; + +struct DeviceInfo { + BindingMappingInfo bindingMappingInfo; }; struct BufferInfo { - BufferUsage usage = BufferUsageBit::NONE; - MemoryUsage memUsage = MemoryUsageBit::NONE; - uint size = 0U; - uint stride = 0U; // in bytes - BufferFlags flags = BufferFlagBit::NONE; + BufferUsage usage{BufferUsageBit::NONE}; + MemoryUsage memUsage{MemoryUsageBit::NONE}; + uint32_t size{0U}; + uint32_t stride{0U}; // in bytes + BufferFlags flags{BufferFlagBit::NONE}; }; struct BufferViewInfo { - Buffer *buffer = nullptr; - uint offset = 0U; - uint range = 0U; + Buffer * buffer{nullptr}; + uint32_t offset{0U}; + uint32_t range{0U}; }; struct DrawInfo { - uint vertexCount = 0U; - uint firstVertex = 0U; - uint indexCount = 0U; - uint firstIndex = 0U; - int vertexOffset = 0; - uint instanceCount = 0U; - uint firstInstance = 0U; + uint32_t vertexCount{0U}; + uint32_t firstVertex{0U}; + uint32_t indexCount{0U}; + uint32_t firstIndex{0U}; + int32_t vertexOffset{0}; + uint32_t instanceCount{0U}; + uint32_t firstInstance{0U}; }; using DrawInfoList = vector; struct DispatchInfo { - uint groupCountX = 0U; - uint groupCountY = 0U; - uint groupCountZ = 0U; + uint32_t groupCountX{0U}; + uint32_t groupCountY{0U}; + uint32_t groupCountZ{0U}; - Buffer *indirectBuffer = nullptr; // @ts-nullable - uint indirectOffset = 0U; + Buffer * indirectBuffer{nullptr}; // @ts-nullable + uint32_t indirectOffset{0U}; }; using DispatchInfoList = vector; @@ -922,132 +952,131 @@ struct IndirectBuffer { }; struct TextureInfo { - TextureType type = TextureType::TEX2D; - TextureUsage usage = TextureUsageBit::NONE; - Format format = Format::UNKNOWN; - uint width = 0U; - uint height = 0U; - TextureFlags flags = TextureFlagBit::NONE; - uint layerCount = 1U; - uint levelCount = 1U; - SampleCount samples = SampleCount::X1; - uint depth = 1U; + TextureType type{TextureType::TEX2D}; + TextureUsage usage{TextureUsageBit::NONE}; + Format format{Format::UNKNOWN}; + uint32_t width{0U}; + uint32_t height{0U}; + TextureFlags flags{TextureFlagBit::NONE}; + uint32_t layerCount{1U}; + uint32_t levelCount{1U}; + SampleCount samples{SampleCount::ONE}; + uint32_t depth{1U}; + void * externalRes{nullptr}; // CVPixelBuffer for Metal, EGLImage for GLES }; struct TextureViewInfo { - Texture * texture = nullptr; - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - uint baseLevel = 0U; - uint levelCount = 1U; - uint baseLayer = 0U; - uint layerCount = 1U; + Texture * texture{nullptr}; + TextureType type{TextureType::TEX2D}; + Format format{Format::UNKNOWN}; + uint32_t baseLevel{0U}; + uint32_t levelCount{1U}; + uint32_t baseLayer{0U}; + uint32_t layerCount{1U}; }; struct SamplerInfo { - Filter minFilter = Filter::LINEAR; - Filter magFilter = Filter::LINEAR; - Filter mipFilter = Filter::NONE; - Address addressU = Address::WRAP; - Address addressV = Address::WRAP; - Address addressW = Address::WRAP; - uint maxAnisotropy = 0U; - ComparisonFunc cmpFunc = ComparisonFunc::ALWAYS; - Color borderColor; - float mipLODBias = 0.0F; + Filter minFilter{Filter::LINEAR}; + Filter magFilter{Filter::LINEAR}; + Filter mipFilter{Filter::NONE}; + Address addressU{Address::WRAP}; + Address addressV{Address::WRAP}; + Address addressW{Address::WRAP}; + uint32_t maxAnisotropy{0U}; + ComparisonFunc cmpFunc{ComparisonFunc::ALWAYS}; }; struct Uniform { - String name; - Type type = Type::UNKNOWN; - uint count = 0U; + String name; + Type type{Type::UNKNOWN}; + uint32_t count{0U}; }; using UniformList = vector; struct UniformBlock { - uint set = 0U; - uint binding = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; String name; UniformList members; - uint count = 0U; + uint32_t count{0U}; }; using UniformBlockList = vector; struct UniformSamplerTexture { - uint set = 0U; - uint binding = 0U; - String name; - Type type = Type::UNKNOWN; - uint count = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; + String name; + Type type{Type::UNKNOWN}; + uint32_t count{0U}; }; using UniformSamplerTextureList = vector; struct UniformSampler { - uint set = 0U; - uint binding = 0U; - String name; - uint count = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; + String name; + uint32_t count{0U}; }; using UniformSamplerList = vector; struct UniformTexture { - uint set = 0U; - uint binding = 0U; - String name; - Type type = Type::UNKNOWN; - uint count = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; + String name; + Type type{Type::UNKNOWN}; + uint32_t count{0U}; }; using UniformTextureList = vector; struct UniformStorageImage { - uint set = 0U; - uint binding = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; String name; - Type type = Type::UNKNOWN; - uint count = 0U; - MemoryAccess memoryAccess = MemoryAccessBit::READ_WRITE; + Type type{Type::UNKNOWN}; + uint32_t count{0U}; + MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; }; using UniformStorageImageList = vector; struct UniformStorageBuffer { - uint set = 0U; - uint binding = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; String name; - uint count = 0U; - MemoryAccess memoryAccess = MemoryAccessBit::READ_WRITE; + uint32_t count{0U}; + MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; }; using UniformStorageBufferList = vector; struct UniformInputAttachment { - uint set = 0U; - uint binding = 0U; - String name; - uint count = 0U; + uint32_t set{0U}; + uint32_t binding{0U}; + String name; + uint32_t count{0U}; }; using UniformInputAttachmentList = vector; struct ShaderStage { - ShaderStageFlagBit stage = ShaderStageFlagBit::NONE; + ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; String source; }; using ShaderStageList = vector; struct Attribute { - String name; - Format format = Format::UNKNOWN; - bool isNormalized = false; - uint stream = 0; - bool isInstanced = false; - uint location = 0; + String name; + Format format{Format::UNKNOWN}; + bool isNormalized{false}; + uint32_t stream{0U}; + bool isInstanced{false}; + uint32_t location{0U}; }; using AttributeList = vector; @@ -1068,51 +1097,51 @@ struct ShaderInfo { struct InputAssemblerInfo { AttributeList attributes; BufferList vertexBuffers; - Buffer * indexBuffer = nullptr; // @ts-nullable - Buffer * indirectBuffer = nullptr; // @ts-nullable + Buffer * indexBuffer{nullptr}; // @ts-nullable + Buffer * indirectBuffer{nullptr}; // @ts-nullable }; struct ColorAttachment { - Format format = Format::UNKNOWN; - SampleCount sampleCount = SampleCount::X1; - LoadOp loadOp = LoadOp::CLEAR; - StoreOp storeOp = StoreOp::STORE; + Format format{Format::UNKNOWN}; + SampleCount sampleCount{SampleCount::ONE}; + LoadOp loadOp{LoadOp::CLEAR}; + StoreOp storeOp{StoreOp::STORE}; std::vector beginAccesses; std::vector endAccesses{AccessType::COLOR_ATTACHMENT_WRITE}; - bool isGeneralLayout = false; + bool isGeneralLayout{false}; }; using ColorAttachmentList = vector; struct DepthStencilAttachment { - Format format = Format::UNKNOWN; - SampleCount sampleCount = SampleCount::X1; - LoadOp depthLoadOp = LoadOp::CLEAR; - StoreOp depthStoreOp = StoreOp::STORE; - LoadOp stencilLoadOp = LoadOp::CLEAR; - StoreOp stencilStoreOp = StoreOp::STORE; + Format format{Format::UNKNOWN}; + SampleCount sampleCount{SampleCount::ONE}; + LoadOp depthLoadOp{LoadOp::CLEAR}; + StoreOp depthStoreOp{StoreOp::STORE}; + LoadOp stencilLoadOp{LoadOp::CLEAR}; + StoreOp stencilStoreOp{StoreOp::STORE}; std::vector beginAccesses; std::vector endAccesses{AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; - bool isGeneralLayout = false; + bool isGeneralLayout{false}; }; struct SubpassInfo { - std::vector inputs; - std::vector colors; - std::vector resolves; - std::vector preserves; + std::vector inputs; + std::vector colors; + std::vector resolves; + std::vector preserves; - uint depthStencil = INVALID_BINDING; - uint depthStencilResolve = INVALID_BINDING; - ResolveMode depthResolveMode = ResolveMode::NONE; - ResolveMode stencilResolveMode = ResolveMode::NONE; + uint32_t depthStencil{INVALID_BINDING}; + uint32_t depthStencilResolve{INVALID_BINDING}; + ResolveMode depthResolveMode{ResolveMode::NONE}; + ResolveMode stencilResolveMode{ResolveMode::NONE}; }; using SubpassInfoList = vector; struct SubpassDependency { - uint srcSubpass = 0U; - uint dstSubpass = 0U; + uint32_t srcSubpass{0U}; + uint32_t dstSubpass{0U}; std::vector srcAccesses; std::vector dstAccesses; }; @@ -1136,24 +1165,24 @@ struct TextureBarrierInfo { std::vector prevAccesses; std::vector nextAccesses; - bool discardContents = false; + bool discardContents{false}; - Queue *srcQueue = nullptr; // @ts-nullable - Queue *dstQueue = nullptr; // @ts-nullable + Queue *srcQueue{nullptr}; // @ts-nullable + Queue *dstQueue{nullptr}; // @ts-nullable }; using TextureBarrierInfoList = vector; struct FramebufferInfo { - RenderPass * renderPass = nullptr; - TextureList colorTextures; // @ts-overrides { type: '(Texture | null)[]' } - Texture * depthStencilTexture = nullptr; // @ts-nullable + RenderPass *renderPass{nullptr}; + TextureList colorTextures; + Texture * depthStencilTexture{nullptr}; // @ts-nullable }; struct DescriptorSetLayoutBinding { - uint binding = INVALID_BINDING; - DescriptorType descriptorType = DescriptorType::UNKNOWN; - uint count = 0; - ShaderStageFlags stageFlags = ShaderStageFlagBit::NONE; + uint32_t binding{INVALID_BINDING}; + DescriptorType descriptorType{DescriptorType::UNKNOWN}; + uint32_t count{0U}; + ShaderStageFlags stageFlags{ShaderStageFlagBit::NONE}; SamplerList immutableSamplers; }; using DescriptorSetLayoutBindingList = vector; @@ -1163,7 +1192,7 @@ struct DescriptorSetLayoutInfo { }; struct DescriptorSetInfo { - DescriptorSetLayout *layout = nullptr; + DescriptorSetLayout *layout{nullptr}; }; struct PipelineLayoutInfo { @@ -1174,122 +1203,122 @@ struct InputState { AttributeList attributes; }; -// Use uint for all boolean values to convert memory to RasterizerState* in shared memory. +// Use uint32_t for all boolean values to convert memory to RasterizerState* in shared memory. struct RasterizerState { - uint isDiscard = 0; - PolygonMode polygonMode = PolygonMode::FILL; - ShadeModel shadeModel = ShadeModel::GOURAND; - CullMode cullMode = CullMode::BACK; - uint isFrontFaceCCW = 1; - uint depthBiasEnabled = 0; - float depthBias = 0.0F; - float depthBiasClamp = 0.0F; - float depthBiasSlop = 0.0F; - uint isDepthClip = 1; - uint isMultisample = 0; - float lineWidth = 1.0F; + uint32_t isDiscard{0U}; + PolygonMode polygonMode{PolygonMode::FILL}; + ShadeModel shadeModel{ShadeModel::GOURAND}; + CullMode cullMode{CullMode::BACK}; + uint32_t isFrontFaceCCW{1U}; + uint32_t depthBiasEnabled{0U}; + float depthBias{0.F}; + float depthBiasClamp{0.F}; + float depthBiasSlop{0.F}; + uint32_t isDepthClip{1U}; + uint32_t isMultisample{0U}; + float lineWidth{1.F}; }; -// Use uint for all boolean values to convert memory to DepthStencilState* in shared memory. +// Use uint32_t for all boolean values to convert memory to DepthStencilState* in shared memory. struct DepthStencilState { - uint depthTest = 1; - uint depthWrite = 1; - ComparisonFunc depthFunc = ComparisonFunc::LESS; - uint stencilTestFront = 0; - ComparisonFunc stencilFuncFront = ComparisonFunc::ALWAYS; - uint stencilReadMaskFront = 0xffffffff; - uint stencilWriteMaskFront = 0xffffffff; - StencilOp stencilFailOpFront = StencilOp::KEEP; - StencilOp stencilZFailOpFront = StencilOp::KEEP; - StencilOp stencilPassOpFront = StencilOp::KEEP; - uint stencilRefFront = 1; - uint stencilTestBack = 0; - ComparisonFunc stencilFuncBack = ComparisonFunc::ALWAYS; - uint stencilReadMaskBack = 0xffffffff; - uint stencilWriteMaskBack = 0xffffffff; - StencilOp stencilFailOpBack = StencilOp::KEEP; - StencilOp stencilZFailOpBack = StencilOp::KEEP; - StencilOp stencilPassOpBack = StencilOp::KEEP; - uint stencilRefBack = 1; + uint32_t depthTest{1U}; + uint32_t depthWrite{1U}; + ComparisonFunc depthFunc{ComparisonFunc::LESS}; + uint32_t stencilTestFront{0U}; + ComparisonFunc stencilFuncFront{ComparisonFunc::ALWAYS}; + uint32_t stencilReadMaskFront{0xffffffffU}; + uint32_t stencilWriteMaskFront{0xffffffffU}; + StencilOp stencilFailOpFront{StencilOp::KEEP}; + StencilOp stencilZFailOpFront{StencilOp::KEEP}; + StencilOp stencilPassOpFront{StencilOp::KEEP}; + uint32_t stencilRefFront{1U}; + uint32_t stencilTestBack{0U}; + ComparisonFunc stencilFuncBack{ComparisonFunc::ALWAYS}; + uint32_t stencilReadMaskBack{0xffffffffU}; + uint32_t stencilWriteMaskBack{0xffffffffU}; + StencilOp stencilFailOpBack{StencilOp::KEEP}; + StencilOp stencilZFailOpBack{StencilOp::KEEP}; + StencilOp stencilPassOpBack{StencilOp::KEEP}; + uint32_t stencilRefBack{1U}; }; -// Use uint for all boolean values to do convert memory to BlendTarget* in shared memory. +// Use uint32_t for all boolean values to do convert memory to BlendTarget* in shared memory. struct BlendTarget { - uint blend = 0; - BlendFactor blendSrc = BlendFactor::ONE; - BlendFactor blendDst = BlendFactor::ZERO; - BlendOp blendEq = BlendOp::ADD; - BlendFactor blendSrcAlpha = BlendFactor::ONE; - BlendFactor blendDstAlpha = BlendFactor::ZERO; - BlendOp blendAlphaEq = BlendOp::ADD; - ColorMask blendColorMask = ColorMask::ALL; + uint32_t blend{0U}; + BlendFactor blendSrc{BlendFactor::ONE}; + BlendFactor blendDst{BlendFactor::ZERO}; + BlendOp blendEq{BlendOp::ADD}; + BlendFactor blendSrcAlpha{BlendFactor::ONE}; + BlendFactor blendDstAlpha{BlendFactor::ZERO}; + BlendOp blendAlphaEq{BlendOp::ADD}; + ColorMask blendColorMask{ColorMask::ALL}; }; using BlendTargetList = vector; -// Use uint for all boolean values to do memeory copy in shared memory. +// Use uint32_t for all boolean values to do memeory copy in shared memory. struct BlendState { - uint isA2C = 0; - uint isIndepend = 0; + uint32_t isA2C{0U}; + uint32_t isIndepend{0U}; Color blendColor; - BlendTargetList targets{1}; + BlendTargetList targets{1U}; }; struct PipelineStateInfo { - Shader * shader = nullptr; - PipelineLayout * pipelineLayout = nullptr; - RenderPass * renderPass = nullptr; + Shader * shader{nullptr}; + PipelineLayout * pipelineLayout{nullptr}; + RenderPass * renderPass{nullptr}; InputState inputState; RasterizerState rasterizerState; DepthStencilState depthStencilState; BlendState blendState; - PrimitiveMode primitive = PrimitiveMode::TRIANGLE_LIST; - DynamicStateFlags dynamicStates = DynamicStateFlagBit::NONE; - PipelineBindPoint bindPoint = PipelineBindPoint::GRAPHICS; - uint subpass = 0U; + PrimitiveMode primitive{PrimitiveMode::TRIANGLE_LIST}; + DynamicStateFlags dynamicStates{DynamicStateFlagBit::NONE}; + PipelineBindPoint bindPoint{PipelineBindPoint::GRAPHICS}; + uint32_t subpass{0U}; }; struct CommandBufferInfo { - Queue * queue = nullptr; - CommandBufferType type = CommandBufferType::PRIMARY; + Queue * queue{nullptr}; + CommandBufferType type{CommandBufferType::PRIMARY}; }; struct QueueInfo { - QueueType type = QueueType::GRAPHICS; + QueueType type{QueueType::GRAPHICS}; }; struct FormatInfo { const String name; - const uint size = 0; - const uint count = 0; - const FormatType type = FormatType::NONE; - const bool hasAlpha = false; - const bool hasDepth = false; - const bool hasStencil = false; - const bool isCompressed = false; + const uint32_t size{0U}; + const uint32_t count{0U}; + const FormatType type{FormatType::NONE}; + const bool hasAlpha{false}; + const bool hasDepth{false}; + const bool hasStencil{false}; + const bool isCompressed{false}; }; struct MemoryStatus { - uint bufferSize = 0; - uint textureSize = 0; + uint32_t bufferSize{0U}; + uint32_t textureSize{0U}; }; struct DynamicStencilStates { - uint writeMask = 0U; - uint compareMask = 0U; - uint reference = 0U; + uint32_t writeMask{0U}; + uint32_t compareMask{0U}; + uint32_t reference{0U}; }; struct DynamicStates { Viewport viewport; Rect scissor; Color blendConstant; - float lineWidth = 1.F; - float depthBiasConstant = 0.F; - float depthBiasClamp = 0.F; - float depthBiasSlope = 0.F; - float depthMinBounds = 0.F; - float depthMaxBounds = 0.F; + float lineWidth{1.F}; + float depthBiasConstant{0.F}; + float depthBiasClamp{0.F}; + float depthBiasSlope{0.F}; + float depthMinBounds{0.F}; + float depthMaxBounds{0.F}; DynamicStencilStates stencilStatesFront; DynamicStencilStates stencilStatesBack; diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index 422beb1b21..c772565480 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -91,12 +91,8 @@ const FormatInfo GFX_FORMAT_INFOS[] = { {"RGB10A2UI", 2, 4, FormatType::UINT, true, false, false, false}, {"RGB9E5", 2, 4, FormatType::FLOAT, true, false, false, false}, - {"D16", 2, 1, FormatType::UINT, false, true, false, false}, - {"D16S8", 3, 1, FormatType::UINT, false, true, true, false}, - {"D24", 3, 1, FormatType::UINT, false, true, false, false}, - {"D24S8", 2, 1, FormatType::UINT, false, true, true, false}, - {"D32F", 4, 1, FormatType::FLOAT, false, true, false, false}, - {"D32FS8", 5, 2, FormatType::FLOAT, false, true, true, false}, + {"DEPTH", 4, 1, FormatType::FLOAT, false, true, false, false}, + {"DEPTH_STENCIL", 5, 2, FormatType::FLOAT, false, true, true, false}, {"BC1", 1, 3, FormatType::UNORM, false, false, false, true}, {"BC1_ALPHA", 1, 4, FormatType::UNORM, true, false, false, true}, diff --git a/native/cocos/renderer/gfx-base/GFXDef.h b/native/cocos/renderer/gfx-base/GFXDef.h index 5d1cd2f648..4fe9b0479a 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.h +++ b/native/cocos/renderer/gfx-base/GFXDef.h @@ -30,51 +30,11 @@ namespace cc { namespace gfx { -enum class VsyncMode { - // The application does not synchronizes with the vertical sync. - // If application renders faster than the display refreshes, frames are wasted and tearing may be observed. - // FPS is uncapped. Maximum power consumption. If unsupported, "ON" value will be used instead. Minimum latency. - OFF, - // The application is always synchronized with the vertical sync. Tearing does not happen. - // FPS is capped to the display's refresh rate. For fast applications, battery life is improved. Always supported. - ON, - // The application synchronizes with the vertical sync, but only if the application rendering speed is greater than refresh rate. - // Compared to OFF, there is no tearing. Compared to ON, the FPS will be improved for "slower" applications. - // If unsupported, "ON" value will be used instead. Recommended for most applications. Default if supported. - RELAXED, - // The presentation engine will always use the latest fully rendered image. - // Compared to OFF, no tearing will be observed. - // Compared to ON, battery power will be worse, especially for faster applications. - // If unsupported, "OFF" will be attempted next. - MAILBOX, - // The application is capped to using half the vertical sync time. - // FPS artificially capped to Half the display speed (usually 30fps) to maintain battery. - // Best possible battery savings. Worst possible performance. - // Recommended for specific applications where battery saving is critical. - HALF, -}; - -struct DeviceInfo { - bool isAntiAlias = false; - uintptr_t windowHandle = 0U; - uint width = 0U; - uint height = 0U; - float pixelRatio = 1.0F; - BindingMappingInfo bindingMappingInfo; -}; - -enum class Performance { - HIGH_QUALITY, - LOW_POWER, - //BALANCE, -}; - -struct ContextInfo { - bool msaaEnabled = false; - Performance performance = Performance::LOW_POWER; - VsyncMode vsyncMode = VsyncMode::RELAXED; - uintptr_t windowHandle = 0; - Context* sharedCtx = nullptr; +struct SwapchainTextureInfo { + Swapchain* swapchain{nullptr}; + Format format{Format::UNKNOWN}; + uint32_t width{0}; + uint32_t height{0}; }; constexpr TextureUsage TEXTURE_USAGE_TRANSIENT = static_cast( diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index cace521ade..2cf476c3bf 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -25,7 +25,6 @@ #include "base/CoreStd.h" -#include "GFXContext.h" #include "GFXDevice.h" #include "GFXObject.h" @@ -47,20 +46,7 @@ Device::~Device() { Device::instance = nullptr; } -Format Device::getColorFormat() const { - return _context->getColorFormat(); -} - -Format Device::getDepthStencilFormat() const { - return _context->getDepthStencilFormat(); -} - bool Device::initialize(const DeviceInfo &info) { - _width = info.width; - _height = info.height; - _pixelRatio = info.pixelRatio; - _windowHandle = info.windowHandle; - _bindingMappingInfo = info.bindingMappingInfo; if (_bindingMappingInfo.bufferOffsets.empty()) { _bindingMappingInfo.bufferOffsets.push_back(0); @@ -73,12 +59,40 @@ bool Device::initialize(const DeviceInfo &info) { } void Device::destroy() { - doDestroy(); + for (auto pair : _samplers) { + CC_SAFE_DELETE(pair.second); + } + + for (auto pair : _globalBarriers) { + CC_SAFE_DELETE(pair.second); + } + + for (auto pair : _textureBarriers) { + CC_SAFE_DELETE(pair.second); + } _bindingMappingInfo.bufferOffsets.clear(); _bindingMappingInfo.samplerOffsets.clear(); - _width = _height = _windowHandle = 0U; - _pixelRatio = 1.0F; + + doDestroy(); +} + +void Device::destroySurface(void *windowHandle) { + for (auto *swapchain :_swapchains) { + if (swapchain->getWindowHandle() == windowHandle) { + swapchain->destroySurface(); + break; + } + } +} + +void Device::createSurface(void *windowHandle) { + for (auto *swapchain :_swapchains) { + if (!swapchain->getWindowHandle()) { + swapchain->createSurface(windowHandle); + break; + } + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 4561c8f6b4..6892ff14a0 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -31,17 +31,18 @@ #include "GFXDescriptorSet.h" #include "GFXDescriptorSetLayout.h" #include "GFXFramebuffer.h" -#include "GFXGlobalBarrier.h" #include "GFXInputAssembler.h" #include "GFXObject.h" #include "GFXPipelineLayout.h" #include "GFXPipelineState.h" #include "GFXQueue.h" #include "GFXRenderPass.h" -#include "GFXSampler.h" #include "GFXShader.h" +#include "GFXSwapchain.h" #include "GFXTexture.h" -#include "GFXTextureBarrier.h" +#include "states/GFXGlobalBarrier.h" +#include "states/GFXSampler.h" +#include "states/GFXTextureBarrier.h" namespace cc { namespace gfx { @@ -55,28 +56,23 @@ public: bool initialize(const DeviceInfo &info); void destroy(); - virtual void resize(uint width, uint height) = 0; - virtual void acquire() = 0; - virtual void present() = 0; + virtual void acquire(Swapchain *const *swapchains, uint32_t count) = 0; + virtual void present() = 0; virtual void flushCommands(CommandBuffer *const *cmdBuffs, uint count) {} - virtual SurfaceTransform getSurfaceTransform() const { return _transform; } - virtual uint getWidth() const { return _width; } - virtual uint getHeight() const { return _height; } - virtual float devicePixelRatio() const { return _pixelRatio; } - virtual MemoryStatus & getMemoryStatus() { return _memoryStatus; } - virtual uint getNumDrawCalls() const { return _numDrawCalls; } - virtual uint getNumInstances() const { return _numInstances; } - virtual uint getNumTris() const { return _numTriangles; } + virtual MemoryStatus &getMemoryStatus() { return _memoryStatus; } + virtual uint getNumDrawCalls() const { return _numDrawCalls; } + virtual uint getNumInstances() const { return _numInstances; } + virtual uint getNumTris() const { return _numTriangles; } inline CommandBuffer * createCommandBuffer(const CommandBufferInfo &info); inline Queue * createQueue(const QueueInfo &info); + inline Swapchain * createSwapchain(const SwapchainInfo &info); inline Buffer * createBuffer(const BufferInfo &info); inline Buffer * createBuffer(const BufferViewInfo &info); inline Texture * createTexture(const TextureInfo &info); inline Texture * createTexture(const TextureViewInfo &info); - inline Sampler * createSampler(const SamplerInfo &info); inline Shader * createShader(const ShaderInfo &info); inline InputAssembler * createInputAssembler(const InputAssemblerInfo &info); inline RenderPass * createRenderPass(const RenderPassInfo &info); @@ -85,15 +81,17 @@ public: inline DescriptorSetLayout *createDescriptorSetLayout(const DescriptorSetLayoutInfo &info); inline PipelineLayout * createPipelineLayout(const PipelineLayoutInfo &info); inline PipelineState * createPipelineState(const PipelineStateInfo &info); - inline GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info); - inline TextureBarrier * createTextureBarrier(const TextureBarrierInfo &info); + + inline Sampler * getSampler(const SamplerInfo &info); + inline GlobalBarrier * getGlobalBarrier(const GlobalBarrierInfo &info); + inline TextureBarrier *getTextureBarrier(const TextureBarrierInfo &info); virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) = 0; - virtual void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) = 0; + virtual void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) = 0; inline void copyBuffersToTexture(const BufferDataList &buffers, Texture *dst, const BufferTextureCopyList ®ions); inline void flushCommands(const vector &cmdBuffs); - inline void flushCommandsForJS(const vector &cmdBuffs); + inline void acquire(const vector &swapchains); inline Queue * getQueue() const { return _queue; } inline CommandBuffer * getCommandBuffer() const { return _cmdBuff; } @@ -106,9 +104,6 @@ public: inline const BindingMappingInfo &bindingMappingInfo() const { return _bindingMappingInfo; } - Format getColorFormat() const; - Format getDepthStencilFormat() const; - protected: static Device *instance; @@ -118,14 +113,17 @@ protected: Device(); + void destroySurface(void *windowHandle); + void createSurface(void *windowHandle); + virtual bool doInit(const DeviceInfo &info) = 0; virtual void doDestroy() = 0; virtual CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) = 0; virtual Queue * createQueue() = 0; + virtual Swapchain * createSwapchain() = 0; virtual Buffer * createBuffer() = 0; virtual Texture * createTexture() = 0; - virtual Sampler * createSampler() = 0; virtual Shader * createShader() = 0; virtual InputAssembler * createInputAssembler() = 0; virtual RenderPass * createRenderPass() = 0; @@ -134,41 +132,39 @@ protected: virtual DescriptorSetLayout *createDescriptorSetLayout() = 0; virtual PipelineLayout * createPipelineLayout() = 0; virtual PipelineState * createPipelineState() = 0; - virtual GlobalBarrier * createGlobalBarrier() = 0; - virtual TextureBarrier * createTextureBarrier() = 0; - // On minimize - virtual void releaseSurface(uintptr_t windowHandle) {} - // On restore - virtual void acquireSurface(uintptr_t windowHandle) {} + virtual Sampler * createSampler(const SamplerInfo &info) = 0; + virtual GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) = 0; + virtual TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) = 0; - virtual void bindRenderContext(bool bound) {} - virtual void bindDeviceContext(bool bound) {} + // For context switching between threads + virtual void bindContext(bool bound) {} - inline Context *getContext() const { return _context; } - - API _api = API::UNKNOWN; - SurfaceTransform _transform = SurfaceTransform::IDENTITY; String _deviceName; String _renderer; String _vendor; String _version; + API _api{API::UNKNOWN}; 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}; - BindingMappingInfo _bindingMappingInfo; DeviceCaps _caps; + BindingMappingInfo _bindingMappingInfo; std::array(Feature::COUNT)> _features; + + Queue * _queue{nullptr}; + CommandBuffer *_cmdBuff{nullptr}; + + uint _numDrawCalls{0U}; + uint _numInstances{0U}; + uint _numTriangles{0U}; + MemoryStatus _memoryStatus; + + unordered_map _samplers; + unordered_map _globalBarriers; + unordered_map _textureBarriers; + +private: + vector _swapchains; }; ////////////////////////////////////////////////////////////////////////// @@ -185,6 +181,13 @@ Queue *Device::createQueue(const QueueInfo &info) { return res; } +Swapchain *Device::createSwapchain(const SwapchainInfo &info) { + Swapchain *res = createSwapchain(); + res->initialize(info); + _swapchains.push_back(res); + return res; +} + Buffer *Device::createBuffer(const BufferInfo &info) { Buffer *res = createBuffer(); res->initialize(info); @@ -209,12 +212,6 @@ Texture *Device::createTexture(const TextureViewInfo &info) { return res; } -Sampler *Device::createSampler(const SamplerInfo &info) { - Sampler *res = createSampler(); - res->initialize(info); - return res; -} - Shader *Device::createShader(const ShaderInfo &info) { Shader *res = createShader(); res->initialize(info); @@ -263,16 +260,28 @@ PipelineState *Device::createPipelineState(const PipelineStateInfo &info) { return res; } -GlobalBarrier *Device::createGlobalBarrier(const GlobalBarrierInfo &info) { - GlobalBarrier *res = createGlobalBarrier(); - res->initialize(info); - return res; +Sampler *Device::getSampler(const SamplerInfo &info) { + uint hash = gfx::Sampler::computeHash(info); + if (!_samplers.count(hash)) { + _samplers[hash] = createSampler(info); + } + return _samplers[hash]; } -TextureBarrier *Device::createTextureBarrier(const TextureBarrierInfo &info) { - TextureBarrier *res = createTextureBarrier(); - res->initialize(info); - return res; +GlobalBarrier *Device::getGlobalBarrier(const GlobalBarrierInfo &info) { + uint hash = gfx::GlobalBarrier::computeHash(info); + if (!_globalBarriers.count(hash)) { + _globalBarriers[hash] = createGlobalBarrier(info); + } + return _globalBarriers[hash]; +} + +TextureBarrier *Device::getTextureBarrier(const TextureBarrierInfo &info) { + uint hash = gfx::TextureBarrier::computeHash(info); + if (!_textureBarriers.count(hash)) { + _textureBarriers[hash] = createTextureBarrier(info); + } + return _textureBarriers[hash]; } void Device::copyBuffersToTexture(const BufferDataList &buffers, Texture *dst, const BufferTextureCopyList ®ions) { @@ -283,8 +292,8 @@ void Device::flushCommands(const vector &cmdBuffs) { flushCommands(cmdBuffs.data(), utils::toUint(cmdBuffs.size())); } -void Device::flushCommandsForJS(const vector &cmdBuffs) { - flushCommands(cmdBuffs.data(), utils::toUint(cmdBuffs.size())); +void Device::acquire(const vector &swapchains) { + acquire(swapchains.data(), utils::toUint(swapchains.size())); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp index f2f13ef0df..62bfe9201d 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp @@ -38,13 +38,15 @@ Framebuffer::Framebuffer() Framebuffer::~Framebuffer() = default; uint Framebuffer::computeHash(const FramebufferInfo &info) { - uint seed = static_cast(info.colorTextures.size() + 2); + uint seed = static_cast(info.colorTextures.size() * 2 + (info.depthStencilTexture ? 2 : 0)); for (const Texture *attachment : info.colorTextures) { - uint id = attachment ? attachment->getObjectID() : 0; - seed ^= id + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= attachment->getHash() + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= attachment->getTypedID() + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } + if (info.depthStencilTexture) { + seed ^= info.depthStencilTexture->getHash() + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= info.depthStencilTexture->getTypedID() + 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-base/GFXInputAssembler.cpp b/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp index 18df68c5c3..72dc00d20c 100644 --- a/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp +++ b/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp @@ -38,16 +38,6 @@ InputAssembler::InputAssembler() InputAssembler::~InputAssembler() = default; -void InputAssembler::extractDrawInfo(DrawInfo &drawInfo) const { - drawInfo.vertexCount = _vertexCount; - drawInfo.firstVertex = _firstVertex; - drawInfo.indexCount = _indexCount; - drawInfo.firstIndex = _firstIndex; - drawInfo.vertexOffset = _vertexOffset; - drawInfo.instanceCount = _instanceCount; - drawInfo.firstInstance = _firstInstance; -} - uint InputAssembler::computeAttributesHash() const { // https://stackoverflow.com/questions/20511347/a-good-hash-function-for-a-vector // 6: Attribute has 6 elements. @@ -68,16 +58,16 @@ void InputAssembler::initialize(const InputAssemblerInfo &info) { _vertexBuffers = info.vertexBuffers; _indexBuffer = info.indexBuffer; _indirectBuffer = info.indirectBuffer; + _attributesHash = computeAttributesHash(); if (_indexBuffer) { - _indexCount = _indexBuffer->getCount(); - _firstIndex = 0; + _drawInfo.indexCount = _indexBuffer->getCount(); + _drawInfo.firstIndex = 0; } else if (!_vertexBuffers.empty()) { - _vertexCount = _vertexBuffers[0]->getCount(); - _firstVertex = 0; - _vertexOffset = 0; + _drawInfo.vertexCount = _vertexBuffers[0]->getCount(); + _drawInfo.firstVertex = 0; + _drawInfo.vertexOffset = 0; } - _attributesHash = computeAttributesHash(); doInit(info); } @@ -86,12 +76,13 @@ void InputAssembler::destroy() { doDestroy(); _attributes.clear(); + _attributesHash = 0U; + _vertexBuffers.clear(); _indexBuffer = nullptr; _indirectBuffer = nullptr; - _indexCount = _firstIndex = _vertexCount = _firstVertex = _vertexOffset = _attributesHash = 0U; - doDestroy(); + _drawInfo = DrawInfo(); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXInputAssembler.h b/native/cocos/renderer/gfx-base/GFXInputAssembler.h index e389010196..71cdca9166 100644 --- a/native/cocos/renderer/gfx-base/GFXInputAssembler.h +++ b/native/cocos/renderer/gfx-base/GFXInputAssembler.h @@ -38,28 +38,21 @@ public: void initialize(const InputAssemblerInfo &info); void destroy(); - void extractDrawInfo(DrawInfo &drawInfo) const; - inline const AttributeList &getAttributes() const { return _attributes; } inline const BufferList & getVertexBuffers() const { return _vertexBuffers; } inline Buffer * getIndexBuffer() const { return _indexBuffer; } inline Buffer * getIndirectBuffer() const { return _indirectBuffer; } - inline uint getVertexCount() const { return _vertexCount; } - inline uint getFirstVertex() const { return _firstVertex; } - inline uint getIndexCount() const { return _indexCount; } - inline uint getFirstIndex() const { return _firstIndex; } - inline uint getVertexOffset() const { return _vertexOffset; } - inline uint getInstanceCount() const { return _instanceCount; } - inline uint getFirstInstance() const { return _firstInstance; } inline uint getAttributesHash() const { return _attributesHash; } - virtual void setVertexCount(uint count) { _vertexCount = count; } - virtual void setFirstVertex(uint first) { _firstVertex = first; } - virtual void setIndexCount(uint count) { _indexCount = count; } - virtual void setFirstIndex(uint first) { _firstIndex = first; } - virtual void setVertexOffset(uint offset) { _vertexOffset = offset; } - virtual void setInstanceCount(uint count) { _instanceCount = count; } - virtual void setFirstInstance(uint first) { _firstInstance = first; } + inline const DrawInfo &getDrawInfo() const { return _drawInfo; } + + virtual void setVertexCount(uint32_t count) { _drawInfo.vertexCount = count; } + virtual void setFirstVertex(uint32_t first) { _drawInfo.firstVertex = first; } + virtual void setIndexCount(uint32_t count) { _drawInfo.indexCount = count; } + virtual void setFirstIndex(uint32_t first) { _drawInfo.firstIndex = first; } + virtual void setVertexOffset(int32_t offset) { _drawInfo.vertexOffset = offset; } + virtual void setInstanceCount(uint32_t count) { _drawInfo.instanceCount = count; } + virtual void setFirstInstance(uint32_t first) { _drawInfo.firstInstance = first; } protected: virtual void doInit(const InputAssemblerInfo &info) = 0; @@ -68,17 +61,13 @@ protected: uint computeAttributesHash() const; AttributeList _attributes; - BufferList _vertexBuffers; - Buffer * _indexBuffer = nullptr; - Buffer * _indirectBuffer = nullptr; - uint _vertexCount = 0; - uint _firstVertex = 0; - uint _indexCount = 0; - uint _firstIndex = 0; - uint _vertexOffset = 0; - uint _instanceCount = 0; - uint _firstInstance = 0; - uint _attributesHash = 0; + uint32_t _attributesHash = 0; + + BufferList _vertexBuffers; + Buffer * _indexBuffer{nullptr}; + Buffer * _indirectBuffer{nullptr}; + + DrawInfo _drawInfo; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXObject.h b/native/cocos/renderer/gfx-base/GFXObject.h index 14b03700c1..6405eff00a 100644 --- a/native/cocos/renderer/gfx-base/GFXObject.h +++ b/native/cocos/renderer/gfx-base/GFXObject.h @@ -39,7 +39,6 @@ public: inline ObjectType getObjectType() const { return _objectType; } inline uint getObjectID() const { return _objectID; } inline uint getTypedID() const { return _typedID; } - inline void resizeObjectID() { _objectID += 10000; } // tempory api protected: template diff --git a/native/cocos/renderer/gfx-base/GFXPipelineLayout.h b/native/cocos/renderer/gfx-base/GFXPipelineLayout.h index 332b1edaad..c14cdeae19 100644 --- a/native/cocos/renderer/gfx-base/GFXPipelineLayout.h +++ b/native/cocos/renderer/gfx-base/GFXPipelineLayout.h @@ -33,7 +33,7 @@ namespace gfx { class CC_DLL PipelineLayout : public GFXObject { public: PipelineLayout(); - virtual ~PipelineLayout(); + ~PipelineLayout() override; void initialize(const PipelineLayoutInfo &info); void destroy(); diff --git a/native/cocos/renderer/gfx-base/GFXQueue.h b/native/cocos/renderer/gfx-base/GFXQueue.h index 27a5ded501..fc8f54335a 100644 --- a/native/cocos/renderer/gfx-base/GFXQueue.h +++ b/native/cocos/renderer/gfx-base/GFXQueue.h @@ -43,8 +43,6 @@ public: inline void submit(const CommandBufferList &cmdBuffs) { submit(cmdBuffs.data(), utils::toUint(cmdBuffs.size())); } - inline void submitForJS(const CommandBufferList &cmdBuffs) { submit(cmdBuffs.data(), utils::toUint(cmdBuffs.size())); } - inline QueueType getType() const { return _type; } protected: diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 0a8abe55d3..28129b8acf 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -59,39 +59,45 @@ uint RenderPass::computeHash() { if (paIndex >= _colorAttachments.size()) break; seed += 2; } - if (subPass.depthStencil < _colorAttachments.size()) { + if (subPass.depthStencil != INVALID_BINDING) { seed += 2; } } - for (const SubpassInfo &subPass : _subpasses) { - for (const uint iaIndex : subPass.inputs) { + for (const SubpassInfo &subpass : _subpasses) { + for (const uint iaIndex : subpass.inputs) { if (iaIndex >= _colorAttachments.size()) break; const ColorAttachment &ia = _colorAttachments[iaIndex]; seed ^= static_cast(ia.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(ia.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - for (const uint caIndex : subPass.colors) { + for (const uint caIndex : subpass.colors) { if (caIndex >= _colorAttachments.size()) break; const ColorAttachment &ca = _colorAttachments[caIndex]; seed ^= static_cast(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(ca.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - for (const uint raIndex : subPass.resolves) { + for (const uint raIndex : subpass.resolves) { if (raIndex >= _colorAttachments.size()) break; const ColorAttachment &ca = _colorAttachments[raIndex]; seed ^= static_cast(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(ca.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - for (const uint paIndex : subPass.preserves) { + for (const uint paIndex : subpass.preserves) { if (paIndex >= _colorAttachments.size()) break; const ColorAttachment &ca = _colorAttachments[paIndex]; seed ^= static_cast(ca.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(ca.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - if (subPass.depthStencil < _colorAttachments.size()) { - const ColorAttachment &ds = _colorAttachments[subPass.depthStencil]; - seed ^= static_cast(ds.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(ds.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + if (subpass.depthStencil != INVALID_BINDING) { + if (subpass.depthStencil < _colorAttachments.size()) { + const auto &ds = _colorAttachments[subpass.depthStencil]; + seed ^= static_cast(ds.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(ds.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } else { + const auto &ds = _depthStencilAttachment; + seed ^= static_cast(ds.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(ds.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } } } } else { @@ -120,32 +126,51 @@ uint RenderPass::computeHash(const RenderPassInfo &info) { seed ^= static_cast(type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }; + static auto computeDSAttachmentHash = [](const DepthStencilAttachment &attachment, uint &seed) { + seed ^= static_cast(attachment.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(attachment.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(attachment.depthLoadOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(attachment.depthStoreOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(attachment.stencilLoadOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(attachment.stencilStoreOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for (AccessType type : attachment.beginAccesses) { + seed ^= static_cast(type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } + for (AccessType type : attachment.endAccesses) { + seed ^= static_cast(type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + } + }; uint seed = 0; if (!info.subpasses.empty()) { - for (const SubpassInfo &subPass : info.subpasses) { - for (const uint iaIndex : subPass.inputs) { + for (const SubpassInfo &subpass : info.subpasses) { + for (const uint iaIndex : subpass.inputs) { if (iaIndex >= info.colorAttachments.size()) break; const ColorAttachment &ia = info.colorAttachments[iaIndex]; seed += 4 + ia.beginAccesses.size() + ia.endAccesses.size(); } - for (const uint caIndex : subPass.colors) { + for (const uint caIndex : subpass.colors) { if (caIndex >= info.colorAttachments.size()) break; const ColorAttachment &ca = info.colorAttachments[caIndex]; seed += 4 + ca.beginAccesses.size() + ca.endAccesses.size(); } - for (const uint raIndex : subPass.resolves) { + for (const uint raIndex : subpass.resolves) { if (raIndex >= info.colorAttachments.size()) break; const ColorAttachment &ra = info.colorAttachments[raIndex]; seed += 4 + ra.beginAccesses.size() + ra.endAccesses.size(); } - for (const uint paIndex : subPass.preserves) { + for (const uint paIndex : subpass.preserves) { if (paIndex >= info.colorAttachments.size()) break; const ColorAttachment &pa = info.colorAttachments[paIndex]; seed += 4 + pa.beginAccesses.size() + pa.endAccesses.size(); } - if (subPass.depthStencil < info.colorAttachments.size()) { - const ColorAttachment &ds = info.colorAttachments[subPass.depthStencil]; - seed += 4 + ds.beginAccesses.size() + ds.endAccesses.size(); + if (subpass.depthStencil != INVALID_BINDING) { + if (subpass.depthStencil < info.colorAttachments.size()) { + const auto &ds = info.colorAttachments[subpass.depthStencil]; + seed += 4 + ds.beginAccesses.size() + ds.endAccesses.size(); + } else { + const auto &ds = info.depthStencilAttachment; + seed += 6 + ds.beginAccesses.size() + ds.endAccesses.size(); + } } } for (const SubpassInfo &subpass : info.subpasses) { @@ -165,8 +190,12 @@ uint RenderPass::computeHash(const RenderPassInfo &info) { if (paIndex >= info.colorAttachments.size()) break; computeAttachmentHash(info.colorAttachments[paIndex], seed); } - if (subpass.depthStencil < info.colorAttachments.size()) { - computeAttachmentHash(info.colorAttachments[subpass.depthStencil], seed); + if (subpass.depthStencil != INVALID_BINDING) { + if (subpass.depthStencil < info.colorAttachments.size()) { + computeAttachmentHash(info.colorAttachments[subpass.depthStencil], seed); + } else { + computeDSAttachmentHash(info.depthStencilAttachment, seed); + } } } } else { @@ -178,18 +207,7 @@ uint RenderPass::computeHash(const RenderPassInfo &info) { for (const ColorAttachment &ca : info.colorAttachments) { computeAttachmentHash(ca, seed); } - seed ^= static_cast(info.depthStencilAttachment.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilAttachment.sampleCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilAttachment.depthLoadOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilAttachment.depthStoreOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilAttachment.stencilLoadOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilAttachment.stencilStoreOp) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - for (AccessType type : info.depthStencilAttachment.beginAccesses) { - seed ^= static_cast(type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - } - for (AccessType type : info.depthStencilAttachment.endAccesses) { - seed ^= static_cast(type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - } + computeDSAttachmentHash(info.depthStencilAttachment, seed); } return seed; diff --git a/native/cocos/renderer/gfx-base/GFXSampler.h b/native/cocos/renderer/gfx-base/GFXSampler.h deleted file mode 100644 index 0fe08381e3..0000000000 --- a/native/cocos/renderer/gfx-base/GFXSampler.h +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "GFXObject.h" - -namespace cc { -namespace gfx { - -class CC_DLL Sampler : public GFXObject { -public: - Sampler(); - ~Sampler() override; - - void initialize(const SamplerInfo &info); - void destroy(); - - inline Filter getMinFilter() const { return _minFilter; } - inline Filter getMagFilter() const { return _magFilter; } - inline Filter getMipFilter() const { return _mipFilter; } - inline Address getAddressU() const { return _addressU; } - inline Address getAddressV() const { return _addressV; } - inline Address getAddressW() const { return _addressW; } - inline uint getMaxAnisotropy() const { return _maxAnisotropy; } - inline ComparisonFunc getCmpFunc() const { return _cmpFunc; } - inline const Color & getBorderColor() const { return _borderColor; } - inline float getMipLODBias() const { return _mipLODBias; } - -protected: - virtual void doInit(const SamplerInfo &info) = 0; - virtual void doDestroy() = 0; - - Filter _minFilter = Filter::NONE; - Filter _magFilter = Filter::NONE; - Filter _mipFilter = Filter::NONE; - Address _addressU = Address::WRAP; - Address _addressV = Address::WRAP; - Address _addressW = Address::WRAP; - uint _maxAnisotropy = 0; - ComparisonFunc _cmpFunc = ComparisonFunc::ALWAYS; - Color _borderColor; - float _mipLODBias = 0.0F; -}; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXSampler.cpp b/native/cocos/renderer/gfx-base/GFXSwapchain.cpp similarity index 65% rename from native/cocos/renderer/gfx-base/GFXSampler.cpp rename to native/cocos/renderer/gfx-base/GFXSwapchain.cpp index 87567f715b..145a237a84 100644 --- a/native/cocos/renderer/gfx-base/GFXSampler.cpp +++ b/native/cocos/renderer/gfx-base/GFXSwapchain.cpp @@ -25,39 +25,40 @@ #include "base/CoreStd.h" -#include "GFXObject.h" -#include "GFXSampler.h" +#include "GFXSwapchain.h" namespace cc { namespace gfx { -Sampler::Sampler() -: GFXObject(ObjectType::SAMPLER) { - _borderColor.x = 0.0F; - _borderColor.y = 0.0F; - _borderColor.z = 0.0F; - _borderColor.w = 0.0F; +Swapchain::Swapchain() +: GFXObject(ObjectType::SWAPCHAIN) { } -Sampler::~Sampler() = default; +Swapchain::~Swapchain() = default; -void Sampler::initialize(const SamplerInfo &info) { - _minFilter = info.minFilter; - _magFilter = info.magFilter; - _mipFilter = info.mipFilter; - _addressU = info.addressU; - _addressV = info.addressV; - _addressW = info.addressW; - _maxAnisotropy = info.maxAnisotropy; - _cmpFunc = info.cmpFunc; - _borderColor = info.borderColor; - _mipLODBias = info.mipLODBias; +void Swapchain::initialize(const SwapchainInfo &info) { + CCASSERT(info.windowHandle, "Invalid window handle"); + + _windowHandle = info.windowHandle; + _vsyncMode = info.vsyncMode; doInit(info); } -void Sampler::destroy() { +void Swapchain::destroy() { doDestroy(); + + _windowHandle = nullptr; +} + +void Swapchain::resize(uint32_t width, uint32_t height, SurfaceTransform transform) { + if (width != _colorTexture->getWidth() || height != _colorTexture->getHeight()) { + doResize(width, height, transform); + + _colorTexture->_info.width = _depthStencilTexture->_info.width = width; + _colorTexture->_info.height = _depthStencilTexture->_info.height = height; + if (isPreRotationEnabled()) _transform = transform; + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXSwapchain.h b/native/cocos/renderer/gfx-base/GFXSwapchain.h new file mode 100644 index 0000000000..44a00b4bd4 --- /dev/null +++ b/native/cocos/renderer/gfx-base/GFXSwapchain.h @@ -0,0 +1,96 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "GFXTexture.h" +#include "gfx-base/GFXDef-common.h" + +namespace cc { +namespace gfx { + +class CC_DLL Swapchain : public GFXObject { +public: + Swapchain(); + ~Swapchain() override; + + void initialize(const SwapchainInfo &info); + void resize(uint32_t width, uint32_t height, SurfaceTransform transform); + void destroy(); + + // TO BE REMOVED + inline void resize(uint32_t width, uint32_t height) { resize(width, height, SurfaceTransform::IDENTITY); } + + inline void destroySurface(); + inline void createSurface(void *windowHandle); + + inline void * getWindowHandle() const { return _windowHandle; } + inline VsyncMode getVSyncMode() const { return _vsyncMode; } + + inline Texture *getColorTexture() const { return _colorTexture; } + inline Texture *getDepthStencilTexture() const { return _depthStencilTexture; } + + inline uint32_t getWidth() const { return _colorTexture->getWidth(); } + inline uint32_t getHeight() const { return _colorTexture->getHeight(); } + inline SurfaceTransform getSurfaceTransform() const { return _transform; } + + virtual bool isPreRotationEnabled() { return _preRotationEnabled; } + +protected: + virtual void doInit(const SwapchainInfo &info) = 0; + virtual void doDestroy() = 0; + virtual void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) = 0; + virtual void doDestroySurface() = 0; + virtual void doCreateSurface(void *windowHandle) = 0; + + static inline void initTexture(const SwapchainTextureInfo &info, Texture *texture); + + void * _windowHandle{nullptr}; + VsyncMode _vsyncMode{VsyncMode::RELAXED}; + SurfaceTransform _transform{SurfaceTransform::IDENTITY}; + bool _preRotationEnabled{false}; + + Texture *_colorTexture{nullptr}; + Texture *_depthStencilTexture{nullptr}; +}; + +/////////////////////////////////////////////////////////// + +void Swapchain::destroySurface() { + doDestroySurface(); + _windowHandle = nullptr; +} + +void Swapchain::createSurface(void *windowHandle) { + _windowHandle = windowHandle; + doCreateSurface(windowHandle); +} + +void Swapchain::initTexture(const SwapchainTextureInfo &info, Texture *texture) { + Texture::initialize(info, texture); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index 228cff86a8..598eebd8b1 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -25,8 +25,7 @@ #include "base/CoreStd.h" -#include "GFXDevice.h" -#include "GFXObject.h" +#include "GFXSwapchain.h" #include "GFXTexture.h" namespace cc { @@ -43,71 +42,112 @@ uint Texture::computeHash(const TextureInfo &info) { seed ^= static_cast(info.type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(info.usage) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= static_cast(info.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(info.flags) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(info.samples) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= (info.width) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= (info.height) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.flags) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= (info.depth) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= (info.layerCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= (info.levelCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.samples) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= (info.depth) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } +uint Texture::computeHash(const TextureViewInfo &info) { + uint seed = 7; + seed ^= static_cast(info.texture->getHash()) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(info.type) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= static_cast(info.format) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= (info.baseLevel) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= (info.levelCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= (info.baseLayer) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + seed ^= (info.layerCount) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + return seed; +} + +uint Texture::computeHash(const Texture *texture) { + uint hash = texture->isTextureView() ? computeHash(texture->getViewInfo()) : computeHash(texture->getInfo()); + if (texture->_swapchain) hash ^= (texture->_swapchain->getObjectID()) + 0x9e3779b9 + (hash << 6) + (hash >> 2); + return hash; +} + void Texture::initialize(const TextureInfo &info) { - _type = info.type; - _usage = info.usage; - _format = info.format; - _width = info.width; - _height = info.height; - _depth = info.depth; - _layerCount = info.layerCount; - _levelCount = info.levelCount; - _samples = info.samples; - _flags = info.flags; - _size = formatSize(_format, _width, _height, _depth); + _info = info; + _size = formatSize(_info.format, _info.width, _info.height, _info.depth); + _hash = computeHash(info); + + _viewInfo.texture = this; + _viewInfo.format = _info.format; + _viewInfo.type = _info.type; + _viewInfo.baseLayer = 0; + _viewInfo.layerCount = _info.layerCount; + _viewInfo.baseLevel = 0; + _viewInfo.levelCount = _info.levelCount; doInit(info); } void Texture::initialize(const TextureViewInfo &info) { - _isTextureView = true; + _info = info.texture->getInfo(); + _viewInfo = info; - _type = info.texture->getType(); - _format = info.format; - _baseLayer = info.baseLayer; - _layerCount = info.layerCount; - _baseLevel = info.baseLevel; - _levelCount = info.levelCount; - _usage = info.texture->getUsage(); - _width = info.texture->getWidth(); - _height = info.texture->getHeight(); - _depth = info.texture->getDepth(); - _samples = info.texture->getSamples(); - _flags = info.texture->getFlags(); - _size = formatSize(_format, _width, _height, _depth); _isTextureView = true; + _size = formatSize(_info.format, _info.width, _info.height, _info.depth); + _hash = computeHash(info); doInit(info); } +void Texture::resize(uint width, uint height) { + if (_info.width != width || _info.height != height) { + uint size = formatSize(_info.format, width, height, _info.depth); + doResize(width, height, size); + + _info.width = width; + _info.height = height; + _size = size; + _hash = computeHash(this); + } +} + void Texture::destroy() { doDestroy(); - _format = Format::UNKNOWN; - _width = _height = _depth = _size = 0; + _info = TextureInfo(); + _viewInfo = TextureViewInfo(); + + _isTextureView = false; + _size = _hash = 0; } -void Texture::resize(uint width, uint height) { - if (_width != width || _height != height) { - uint size = formatSize(_format, width, height, _depth); - doResize(width, height, size); +///////////////////////////// Swapchian Specific ///////////////////////////// - _width = width; - _height = height; - _size = size; +void Texture::initialize(const SwapchainTextureInfo &info, Texture *out) { + out->_info.type = TextureType::TEX2D; + out->_info.format = info.format; + out->_info.width = info.width; + out->_info.height = info.height; + out->_info.layerCount = 1; + out->_info.levelCount = 1; + out->_info.depth = 1; + out->_info.samples = SampleCount::ONE; + out->_info.flags = TextureFlagBit::NONE; + out->_info.usage = GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth + ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT + : TextureUsageBit::COLOR_ATTACHMENT; - resizeObjectID(); - } + out->_swapchain = info.swapchain; + out->_size = formatSize(info.format, info.width, info.height, 1); + out->_hash = computeHash(out); + + out->_viewInfo.texture = out; + out->_viewInfo.format = out->_info.format; + out->_viewInfo.type = out->_info.type; + out->_viewInfo.baseLayer = 0; + out->_viewInfo.layerCount = out->_info.layerCount; + out->_viewInfo.baseLevel = 0; + out->_viewInfo.levelCount = out->_info.levelCount; + + out->doInit(info); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXTexture.h b/native/cocos/renderer/gfx-base/GFXTexture.h index 74dea5fa18..1ee7ac1782 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.h +++ b/native/cocos/renderer/gfx-base/GFXTexture.h @@ -35,46 +35,45 @@ public: Texture(); ~Texture() override; - static uint computeHash(const TextureInfo &info); + static uint32_t computeHash(const TextureInfo &info); + static uint32_t computeHash(const TextureViewInfo &info); void initialize(const TextureInfo &info); void initialize(const TextureViewInfo &info); + void resize(uint32_t width, uint32_t height); void destroy(); - void resize(uint width, uint height); - inline TextureType getType() const { return _type; } - inline TextureUsage getUsage() const { return _usage; } - inline Format getFormat() const { return _format; } - inline uint getWidth() const { return _width; } - inline uint getHeight() const { return _height; } - inline uint getDepth() const { return _depth; } - inline uint getLayerCount() const { return _layerCount; } - inline uint getLevelCount() const { return _levelCount; } - inline uint getSize() const { return _size; } - inline SampleCount getSamples() const { return _samples; } - inline TextureFlags getFlags() const { return _flags; } - inline bool isTextureView() const { return _isTextureView; } + inline const TextureInfo & getInfo() const { return _info; } + inline const TextureViewInfo &getViewInfo() const { return _viewInfo; } + + inline bool isTextureView() const { return _isTextureView; } + inline uint32_t getSize() const { return _size; } + inline uint32_t getHash() const { return _hash; } + + // convenient getter for common usages + inline Format getFormat() const { return _info.format; } + inline uint32_t getWidth() const { return _info.width; } + inline uint32_t getHeight() const { return _info.height; } protected: - virtual void doInit(const TextureInfo &info) = 0; - virtual void doInit(const TextureViewInfo &info) = 0; - virtual void doDestroy() = 0; - virtual void doResize(uint width, uint height, uint size) = 0; + friend class Swapchain; - TextureType _type = TextureType::TEX2D; - TextureUsage _usage = TextureUsageBit::NONE; - Format _format = Format::UNKNOWN; - uint _width = 0U; - uint _height = 0U; - uint _depth = 1U; - uint _baseLevel = 0U; - uint _levelCount = 1U; - uint _baseLayer = 0U; - uint _layerCount = 1U; - uint _size = 0U; - SampleCount _samples = SampleCount::X1; - TextureFlags _flags = TextureFlagBit::NONE; - bool _isTextureView = false; + virtual void doInit(const TextureInfo &info) = 0; + virtual void doInit(const TextureViewInfo &info) = 0; + virtual void doDestroy() = 0; + virtual void doResize(uint32_t width, uint32_t height, uint32_t size) = 0; + + static uint32_t computeHash(const Texture *texture); + static void initialize(const SwapchainTextureInfo &info, Texture *out); + virtual void doInit(const SwapchainTextureInfo &info) = 0; + + TextureInfo _info; + TextureViewInfo _viewInfo; + + Swapchain *_swapchain{nullptr}; + bool _isTextureView{false}; + uint32_t _size{0U}; + uint32_t _hash{0U}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp new file mode 100644 index 0000000000..f0002a4ddb --- /dev/null +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp @@ -0,0 +1,236 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "SPIRVUtils.h" + +#include "base/Log.h" +#include "base/Utils.h" +#include "glslang/Public/ShaderLang.h" +#include "glslang/SPIRV/GlslangToSpv.h" +#include "glslang/StandAlone/ResourceLimits.h" +#include "spirv/spirv.h" + +namespace cc { +namespace gfx { + +namespace { +EShLanguage getShaderStage(ShaderStageFlagBit type) { + switch (type) { + case ShaderStageFlagBit::VERTEX: return EShLangVertex; + case ShaderStageFlagBit::CONTROL: return EShLangTessControl; + case ShaderStageFlagBit::EVALUATION: return EShLangTessEvaluation; + case ShaderStageFlagBit::GEOMETRY: return EShLangGeometry; + case ShaderStageFlagBit::FRAGMENT: return EShLangFragment; + case ShaderStageFlagBit::COMPUTE: return EShLangCompute; + default: { + CCASSERT(false, "Unsupported ShaderStageFlagBit, convert to EShLanguage failed."); + return EShLangVertex; + } + } +} + +glslang::EShTargetClientVersion getClientVersion(int vulkanMinorVersion) { + switch (vulkanMinorVersion) { + case 0: return glslang::EShTargetVulkan_1_0; + case 1: return glslang::EShTargetVulkan_1_1; + case 2: return glslang::EShTargetVulkan_1_2; + default: { + CCASSERT(false, "Unsupported vulkan version, convert to EShTargetClientVersion failed."); + return glslang::EShTargetVulkan_1_0; + } + } +} + +glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { + switch (vulkanMinorVersion) { + case 0: return glslang::EShTargetSpv_1_0; + case 1: return glslang::EShTargetSpv_1_3; + case 2: return glslang::EShTargetSpv_1_5; + default: { + CCASSERT(false, "Unsupported vulkan version, convert to EShTargetLanguageVersion failed."); + return glslang::EShTargetSpv_1_0; + } + } +} + +// https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.pdf +struct Id { + uint32_t opcode{0}; + uint32_t typeId{0}; + uint32_t storageClass{0}; + uint32_t* pLocation{nullptr}; +}; +} // namespace + +SPIRVUtils SPIRVUtils::instance; + +void SPIRVUtils::initialize(int vulkanMinorVersion) { + glslang::InitializeProcess(); + + _clientInputSemanticsVersion = 100 + vulkanMinorVersion * 10; + _clientVersion = getClientVersion(vulkanMinorVersion); + _targetVersion = getTargetVersion(vulkanMinorVersion); +} + +void SPIRVUtils::destroy() { + glslang::FinalizeProcess(); + _output.clear(); +} + +void SPIRVUtils::compileGLSL(ShaderStageFlagBit type, const String& source) { + EShLanguage stage = getShaderStage(type); + const char* string = source.c_str(); + + _shader = std::make_unique(stage); + _shader->setStrings(&string, 1); + + _shader->setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientVulkan, _clientInputSemanticsVersion); + _shader->setEnvClient(glslang::EShClientVulkan, _clientVersion); + _shader->setEnvTarget(glslang::EShTargetSpv, _targetVersion); + + auto messages = static_cast(EShMsgSpvRules | EShMsgVulkanRules); + + if (!_shader->parse(&glslang::DefaultTBuiltInResource, _clientInputSemanticsVersion, false, messages)) { + CC_LOG_ERROR("GLSL Parsing Failed:\n%s\n%s", _shader->getInfoLog(), _shader->getInfoDebugLog()); + } + + _program = std::make_unique(); + _program->addShader(_shader.get()); + + if (!_program->link(messages)) { + CC_LOG_ERROR("GLSL Linking Failed:\n%s\n%s", _program->getInfoLog(), _program->getInfoDebugLog()); + } + + _output.clear(); + spv::SpvBuildLogger logger; + glslang::SpvOptions spvOptions; + spvOptions.disableOptimizer = false; +#if CC_DEBUG > 0 + //spvOptions.validate = true; +#else + spvOptions.optimizeSize = true; + spvOptions.stripDebugInfo = true; +#endif + glslang::GlslangToSpv(*_program->getIntermediate(stage), _output, &logger, &spvOptions); +} + +void SPIRVUtils::compressInputLocations(gfx::AttributeList& attributes) { + static std::vector ids; + static vector activeLocations; + static vector newLocations; + + uint32_t* code = _output.data(); + uint32_t codeSize = utils::toUint(_output.size()); + + CC_ASSERT(code[0] == SpvMagicNumber); + + uint32_t idBound = code[3]; + ids.assign(idBound, {}); + + uint32_t* insn = code + 5; + while (insn != code + codeSize) { + auto opcode = static_cast(insn[0]); + auto wordCount = static_cast(insn[0] >> 16); + + switch (opcode) { + case SpvOpDecorate: { + CC_ASSERT(wordCount >= 3); + + uint32_t id = insn[1]; + CC_ASSERT(id < idBound); + + switch (insn[2]) { + case SpvDecorationLocation: + CC_ASSERT(wordCount == 4); + ids[id].pLocation = &insn[3]; + break; + } + } break; + case SpvOpVariable: { + CC_ASSERT(wordCount >= 4); + + uint32_t id = insn[2]; + CC_ASSERT(id < idBound); + + CC_ASSERT(ids[id].opcode == 0); + ids[id].opcode = opcode; + ids[id].typeId = insn[1]; + ids[id].storageClass = insn[3]; + } break; + } + + CC_ASSERT(insn + wordCount <= code + codeSize); + insn += wordCount; + } + + _program->buildReflection(); + activeLocations.clear(); + int activeCount = _program->getNumPipeInputs(); + for (int i = 0; i < activeCount; ++i) { + activeLocations.push_back(_program->getPipeInput(i).getType()->getQualifier().layoutLocation); + } + + uint32_t location = 0; + uint32_t unusedLocation = activeCount; + newLocations.assign(attributes.size(), UINT_MAX); + + for (auto& id : ids) { + if (id.opcode == SpvOpVariable && id.storageClass == SpvStorageClassInput) { + uint32_t oldLocation = *id.pLocation; + + // update locations in SPIRV + if (std::find(activeLocations.begin(), activeLocations.end(), *id.pLocation) != activeLocations.end()) { + *id.pLocation = location++; + } else { + *id.pLocation = unusedLocation++; + } + + // save record + bool found{false}; + for (size_t i = 0; i < attributes.size(); ++i) { + if (attributes[i].location == oldLocation) { + newLocations[i] = *id.pLocation; + found = true; + break; + } + } + + CCASSERT(found, "missing attribute declarations?"); + } + } + + // update gfx references + for (size_t i = 0; i < attributes.size(); ++i) { + attributes[i].location = newLocations[i]; + } + + attributes.erase(std::remove_if(attributes.begin(), attributes.end(), [](const auto& attr) { + return attr.location == UINT_MAX; + }), + attributes.end()); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.h b/native/cocos/renderer/gfx-base/SPIRVUtils.h new file mode 100644 index 0000000000..b9d05033e4 --- /dev/null +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "gfx-base/GFXDef.h" +#include "glslang/Public/ShaderLang.h" + +namespace cc { +namespace gfx { + +class SPIRVUtils { +public: + static SPIRVUtils* getInstance() { return &instance; } + + void initialize(int vulkanMinorVersion); + void destroy(); + + void compileGLSL(ShaderStageFlagBit type, const String& source); + void compressInputLocations(gfx::AttributeList& attributes); + + inline uint32_t* getOutputData() { + _shader.reset(); + _program.reset(); + return _output.data(); + } + + inline size_t getOutputSize() { + return _output.size() * sizeof(uint32_t); + } + +private: + int _clientInputSemanticsVersion{0}; + glslang::EShTargetClientVersion _clientVersion{glslang::EShTargetClientVersion::EShTargetVulkan_1_0}; + glslang::EShTargetLanguageVersion _targetVersion{glslang::EShTargetLanguageVersion::EShTargetSpv_1_0}; + + std::unique_ptr _shader{nullptr}; + std::unique_ptr _program{nullptr}; + vector _output; + + static SPIRVUtils instance; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXGlobalBarrier.cpp b/native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.cpp similarity index 93% rename from native/cocos/renderer/gfx-base/GFXGlobalBarrier.cpp rename to native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.cpp index 5b06714394..4400b8d591 100644 --- a/native/cocos/renderer/gfx-base/GFXGlobalBarrier.cpp +++ b/native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.cpp @@ -26,18 +26,15 @@ #include "base/CoreStd.h" #include "GFXGlobalBarrier.h" -#include "GFXObject.h" namespace cc { namespace gfx { -GlobalBarrier::GlobalBarrier() +GlobalBarrier::GlobalBarrier(const GlobalBarrierInfo &info) : GFXObject(ObjectType::GLOBAL_BARRIER) { - _typedID = generateObjectID(); + _info = info; } -GlobalBarrier::~GlobalBarrier() = default; - uint GlobalBarrier::computeHash(const GlobalBarrierInfo &info) { uint seed = static_cast(info.prevAccesses.size() + info.nextAccesses.size()); diff --git a/native/cocos/renderer/gfx-base/GFXGlobalBarrier.h b/native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.h similarity index 83% rename from native/cocos/renderer/gfx-base/GFXGlobalBarrier.h rename to native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.h index 874c06ff0c..7a02a3f5a7 100644 --- a/native/cocos/renderer/gfx-base/GFXGlobalBarrier.h +++ b/native/cocos/renderer/gfx-base/states/GFXGlobalBarrier.h @@ -25,29 +25,20 @@ #pragma once -#include "GFXObject.h" +#include "../GFXObject.h" namespace cc { namespace gfx { class CC_DLL GlobalBarrier : public GFXObject { public: - GlobalBarrier(); - ~GlobalBarrier() override; + explicit GlobalBarrier(const GlobalBarrierInfo &info); static uint computeHash(const GlobalBarrierInfo &info); - inline const GlobalBarrierInfo &info() const { return _info; } + inline const GlobalBarrierInfo &getInfo() const { return _info; } protected: - friend class Device; - - virtual void doInit(const GlobalBarrierInfo &info) {} - - void initialize(const GlobalBarrierInfo &info) { - _info = info; doInit(info); - } - GlobalBarrierInfo _info; }; diff --git a/native/cocos/renderer/gfx-metal/MTLContext.h b/native/cocos/renderer/gfx-base/states/GFXSampler.cpp similarity index 71% rename from native/cocos/renderer/gfx-metal/MTLContext.h rename to native/cocos/renderer/gfx-base/states/GFXSampler.cpp index dac5e3120c..b81ff46144 100644 --- a/native/cocos/renderer/gfx-metal/MTLContext.h +++ b/native/cocos/renderer/gfx-base/states/GFXSampler.cpp @@ -23,28 +23,29 @@ THE SOFTWARE. ****************************************************************************/ -#pragma once +#include "base/CoreStd.h" -#include "gfx-base/GFXContext.h" +#include "GFXSampler.h" namespace cc { namespace gfx { -class CCMTLContext final : public Context { -public: - explicit CCMTLContext(); - ~CCMTLContext() override = default; - CCMTLContext(const CCMTLContext &)=delete; - CCMTLContext(CCMTLContext &&)=delete; - CCMTLContext &operator=(const CCMTLContext &)=delete; - CCMTLContext &operator=(CCMTLContext &&)=delete; +Sampler::Sampler(const SamplerInfo &info) +: GFXObject(ObjectType::SAMPLER) { + _info = info; +} - void present() override {} - -protected: - bool doInit(const ContextInfo &info) override; - void doDestroy() override {} -}; +uint32_t Sampler::computeHash(const SamplerInfo &info) { + uint32_t hash = toNumber(info.minFilter); + hash |= (toNumber(info.magFilter) << 2); + hash |= (toNumber(info.mipFilter) << 4); + hash |= (toNumber(info.addressU) << 6); + hash |= (toNumber(info.addressV) << 8); + hash |= (toNumber(info.addressW) << 10); + hash |= (info.maxAnisotropy << 12); + hash |= (toNumber(info.cmpFunc) << 16); + return hash; +} } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyContext.h b/native/cocos/renderer/gfx-base/states/GFXSampler.h similarity index 83% rename from native/cocos/renderer/gfx-empty/EmptyContext.h rename to native/cocos/renderer/gfx-base/states/GFXSampler.h index 835eca9b8b..8b555b94f6 100644 --- a/native/cocos/renderer/gfx-empty/EmptyContext.h +++ b/native/cocos/renderer/gfx-base/states/GFXSampler.h @@ -25,18 +25,22 @@ #pragma once -#include "gfx-base/GFXContext.h" +#include "../GFXObject.h" +#include "gfx-base/GFXDef-common.h" namespace cc { namespace gfx { -class CC_DLL EmptyContext final : public Context { +class CC_DLL Sampler : public GFXObject { public: - void present() override; + explicit Sampler(const SamplerInfo &info); + + static uint32_t computeHash(const SamplerInfo &info); + + inline const SamplerInfo &getInfo() const { return _info; } protected: - bool doInit(const ContextInfo &info) override; - void doDestroy() override; + SamplerInfo _info; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXTextureBarrier.cpp b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.cpp similarity index 93% rename from native/cocos/renderer/gfx-base/GFXTextureBarrier.cpp rename to native/cocos/renderer/gfx-base/states/GFXTextureBarrier.cpp index c5265ac70f..605d89d1c0 100644 --- a/native/cocos/renderer/gfx-base/GFXTextureBarrier.cpp +++ b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.cpp @@ -25,20 +25,17 @@ #include "base/CoreStd.h" -#include "GFXObject.h" -#include "GFXQueue.h" +#include "../GFXQueue.h" #include "GFXTextureBarrier.h" namespace cc { namespace gfx { -TextureBarrier::TextureBarrier() +TextureBarrier::TextureBarrier(const TextureBarrierInfo &info) : GFXObject(ObjectType::TEXTURE_BARRIER) { - _typedID = generateObjectID(); + _info = info; } -TextureBarrier::~TextureBarrier() = default; - uint TextureBarrier::computeHash(const TextureBarrierInfo &info) { uint seed = static_cast(info.prevAccesses.size() + info.nextAccesses.size() + 3); diff --git a/native/cocos/renderer/gfx-base/GFXTextureBarrier.h b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h similarity index 82% rename from native/cocos/renderer/gfx-base/GFXTextureBarrier.h rename to native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h index d4bc7b4ba2..03905b565c 100644 --- a/native/cocos/renderer/gfx-base/GFXTextureBarrier.h +++ b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h @@ -25,30 +25,20 @@ #pragma once -#include "GFXObject.h" +#include "../GFXObject.h" namespace cc { namespace gfx { class CC_DLL TextureBarrier : public GFXObject { public: - TextureBarrier(); - ~TextureBarrier() override; + explicit TextureBarrier(const TextureBarrierInfo &info); static uint computeHash(const TextureBarrierInfo &info); - inline const TextureBarrierInfo &info() const { return _info; } + inline const TextureBarrierInfo &getInfo() const { return _info; } protected: - friend class Device; - - virtual void doInit(const TextureBarrierInfo &info) {} - - void initialize(const TextureBarrierInfo &info) { - _info = info; - doInit(info); - } - TextureBarrierInfo _info; }; diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp index d2b1ca65e6..45f4e243c5 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp @@ -27,7 +27,6 @@ #include "EmptyBuffer.h" #include "EmptyCommandBuffer.h" -#include "EmptyContext.h" #include "EmptyDescriptorSet.h" #include "EmptyDescriptorSetLayout.h" #include "EmptyDevice.h" @@ -37,8 +36,8 @@ #include "EmptyPipelineState.h" #include "EmptyQueue.h" #include "EmptyRenderPass.h" -#include "EmptySampler.h" #include "EmptyShader.h" +#include "EmptySwapchain.h" #include "EmptyTexture.h" namespace cc { @@ -59,15 +58,6 @@ EmptyDevice::~EmptyDevice() { } bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - - _context = CC_NEW(EmptyContext); - if (!_context->initialize(ctxInfo)) { - destroy(); - return false; - } - QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); @@ -78,7 +68,6 @@ bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { _cmdBuff = createCommandBuffer(cmdBuffInfo); CC_LOG_INFO("Empty device initialized."); - CC_LOG_INFO("SCREEN_SIZE: %d x %d", _width, _height); return true; } @@ -86,15 +75,9 @@ bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { void EmptyDevice::doDestroy() { CC_SAFE_DESTROY(_cmdBuff); CC_SAFE_DESTROY(_queue); - CC_SAFE_DESTROY(_context); } -void EmptyDevice::resize(uint width, uint height) { - _width = width; - _height = height; -} - -void EmptyDevice::acquire() { +void EmptyDevice::acquire(Swapchain *const *swapchains, uint32_t count) { } void EmptyDevice::present() { @@ -109,6 +92,10 @@ Queue *EmptyDevice::createQueue() { return CC_NEW(EmptyQueue()); } +Swapchain *EmptyDevice::createSwapchain() { + return CC_NEW(EmptySwapchain()); +} + Buffer *EmptyDevice::createBuffer() { return CC_NEW(EmptyBuffer()); } @@ -117,10 +104,6 @@ Texture *EmptyDevice::createTexture() { return CC_NEW(EmptyTexture()); } -Sampler *EmptyDevice::createSampler() { - return CC_NEW(EmptySampler()); -} - Shader *EmptyDevice::createShader() { return CC_NEW(EmptyShader()); } @@ -153,12 +136,16 @@ PipelineState *EmptyDevice::createPipelineState() { return CC_NEW(EmptyPipelineState()); } -GlobalBarrier *EmptyDevice::createGlobalBarrier() { - return CC_NEW(GlobalBarrier()); +Sampler *EmptyDevice::createSampler(const SamplerInfo &info) { + return CC_NEW(Sampler(info)); } -TextureBarrier *EmptyDevice::createTextureBarrier() { - return CC_NEW(TextureBarrier()); +GlobalBarrier *EmptyDevice::createGlobalBarrier(const GlobalBarrierInfo &info) { + return CC_NEW(GlobalBarrier(info)); +} + +TextureBarrier *EmptyDevice::createTextureBarrier(const TextureBarrierInfo &info) { + return CC_NEW(TextureBarrier(info)); } void EmptyDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.h b/native/cocos/renderer/gfx-empty/EmptyDevice.h index 0506ffc2e8..c8004bb0d8 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.h +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.h @@ -26,6 +26,7 @@ #pragma once #include "gfx-base/GFXDevice.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { @@ -50,18 +51,18 @@ public: using Device::createRenderPass; using Device::createSampler; using Device::createShader; + using Device::createSwapchain; using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool emptyhas) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -70,10 +71,13 @@ public: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; + + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; protected: static EmptyDevice *instance; diff --git a/native/cocos/renderer/gfx-empty/EmptySampler.cpp b/native/cocos/renderer/gfx-empty/EmptySampler.cpp deleted file mode 100644 index de1a9285bb..0000000000 --- a/native/cocos/renderer/gfx-empty/EmptySampler.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "EmptySampler.h" - -namespace cc { -namespace gfx { - -void EmptySampler::doInit(const SamplerInfo &info) { -} - -void EmptySampler::doDestroy() { -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-validator/SamplerValidator.cpp b/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp similarity index 61% rename from native/cocos/renderer/gfx-validator/SamplerValidator.cpp rename to native/cocos/renderer/gfx-empty/EmptySwapchain.cpp index 43e6162eff..d7a0ea1aca 100644 --- a/native/cocos/renderer/gfx-validator/SamplerValidator.cpp +++ b/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -23,33 +23,40 @@ THE SOFTWARE. ****************************************************************************/ +#include "EmptySwapchain.h" +#include "EmptyTexture.h" #include "base/CoreStd.h" -#include "base/threading/MessageQueue.h" - -#include "DescriptorSetLayoutValidator.h" -#include "DeviceValidator.h" -#include "SamplerValidator.h" -#include "ValidationUtils.h" namespace cc { namespace gfx { -SamplerValidator::SamplerValidator(Sampler *actor) -: Agent(actor) { - _typedID = generateObjectID(); +void EmptySwapchain::doInit(const SwapchainInfo &info) { + _colorTexture = CC_NEW(EmptyTexture); + _depthStencilTexture = CC_NEW(EmptyTexture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = Format::DEPTH_STENCIL; + initTexture(textureInfo, _depthStencilTexture); } -SamplerValidator::~SamplerValidator() { - DeviceResourceTracker::erase(this); - CC_SAFE_DELETE(_actor); +void EmptySwapchain::doDestroy() { + CC_SAFE_DESTROY(_depthStencilTexture); + CC_SAFE_DESTROY(_colorTexture); } -void SamplerValidator::doInit(const SamplerInfo &info) { - _actor->initialize(info); +void EmptySwapchain::doResize(uint width, uint height, SurfaceTransform transform) { } -void SamplerValidator::doDestroy() { - _actor->destroy(); +void EmptySwapchain::doDestroySurface() { +} + +void EmptySwapchain::doCreateSurface(void *windowHandle) { } } // namespace gfx diff --git a/native/cocos/renderer/gfx-agent/SamplerAgent.h b/native/cocos/renderer/gfx-empty/EmptySwapchain.h similarity index 79% rename from native/cocos/renderer/gfx-agent/SamplerAgent.h rename to native/cocos/renderer/gfx-empty/EmptySwapchain.h index 1412d4b0e6..3bf6defa3b 100644 --- a/native/cocos/renderer/gfx-agent/SamplerAgent.h +++ b/native/cocos/renderer/gfx-empty/EmptySwapchain.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,20 +25,19 @@ #pragma once -#include "base/Agent.h" -#include "gfx-base/GFXSampler.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { -class CC_DLL SamplerAgent final : public Agent { +class CC_DLL EmptySwapchain final : public Swapchain { public: - explicit SamplerAgent(Sampler *actor); - ~SamplerAgent() override; - protected: - void doInit(const SamplerInfo &info) override; + void doInit(const SwapchainInfo &info) override; void doDestroy() override; + void doResize(uint width, uint height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-empty/EmptyTexture.cpp b/native/cocos/renderer/gfx-empty/EmptyTexture.cpp index 550d2ce745..42c7878545 100644 --- a/native/cocos/renderer/gfx-empty/EmptyTexture.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyTexture.cpp @@ -24,6 +24,7 @@ ****************************************************************************/ #include "EmptyTexture.h" +#include "gfx-base/GFXDef.h" namespace cc { namespace gfx { @@ -34,6 +35,9 @@ void EmptyTexture::doInit(const TextureInfo &info) { void EmptyTexture::doInit(const TextureViewInfo &info) { } +void EmptyTexture::doInit(const SwapchainTextureInfo &info) { +} + void EmptyTexture::doDestroy() { } diff --git a/native/cocos/renderer/gfx-empty/EmptyTexture.h b/native/cocos/renderer/gfx-empty/EmptyTexture.h index fd21174f9f..81533ad7fb 100644 --- a/native/cocos/renderer/gfx-empty/EmptyTexture.h +++ b/native/cocos/renderer/gfx-empty/EmptyTexture.h @@ -25,6 +25,7 @@ #pragma once +#include "gfx-base/GFXDef.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -35,6 +36,7 @@ public: protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; + void doInit(const SwapchainTextureInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; }; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index 01a1f3252b..c45a74efb6 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -27,6 +27,7 @@ #include "GLES2Buffer.h" #include "GLES2CommandBuffer.h" +#include "GLES2Commands.h" #include "GLES2DescriptorSet.h" #include "GLES2Device.h" #include "GLES2Framebuffer.h" @@ -34,7 +35,6 @@ #include "GLES2PipelineState.h" #include "GLES2RenderPass.h" #include "GLES2Texture.h" -#include "gfx-base/GFXDef-common.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index 20a6cea807..3fb68bf9f8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -25,12 +25,16 @@ #pragma once -#include "GLES2Commands.h" +#include "GLES2Std.h" #include "gfx-base/GFXCommandBuffer.h" namespace cc { namespace gfx { +class GLES2CmdPackage; +class GLES2GPUPipelineState; +class GLES2GPUDescriptorSet; +class GLES2GPUInputAssembler; class GLES2GPUCommandAllocator; class CC_GLES2_API GLES2CommandBuffer : public CommandBuffer { diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index bce176d555..4b846210b7 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -27,7 +27,6 @@ #include "GLES2Commands.h" #include "GLES2Device.h" -#include "gfx-gles-common/GLESCommandPool.h" #define BUFFER_OFFSET(idx) (static_cast(0) + (idx)) @@ -66,12 +65,8 @@ GLenum mapGLFormat(Format format) { case Format::RGB10A2: case Format::SRGB8_A8: return GL_RGBA; - 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::DEPTH: return GL_DEPTH_COMPONENT; + case Format::DEPTH_STENCIL: 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; @@ -147,10 +142,8 @@ GLenum mapGLInternalFormat(Format format) { 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; + case Format::DEPTH: return GL_DEPTH_COMPONENT16; + case Format::DEPTH_STENCIL: return GL_DEPTH24_STENCIL8_OES; default: return mapGLFormat(format); } @@ -266,12 +259,8 @@ GLenum formatToGLType(Format format) { case Format::R11G11B10F: return GL_FLOAT; case Format::RGB9E5: return GL_FLOAT; - case Format::D16: return GL_UNSIGNED_SHORT; - case Format::D16S8: return GL_UNSIGNED_INT_24_8_OES; - case Format::D24: return GL_UNSIGNED_INT; - case Format::D24S8: return GL_UNSIGNED_INT_24_8_OES; - case Format::D32F: return GL_UNSIGNED_INT; - case Format::D32F_S8: return GL_UNSIGNED_INT_24_8_OES; + case Format::DEPTH: return GL_UNSIGNED_SHORT; + case Format::DEPTH_STENCIL: return GL_UNSIGNED_INT_24_8_OES; case Format::BC1: case Format::BC1_SRGB: @@ -596,7 +585,7 @@ void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) gpuTexture->glType = formatToGLType(gpuTexture->format); gpuTexture->glInternalFmt = gpuTexture->glFormat; - if (gpuTexture->samples > SampleCount::X1) { + if (gpuTexture->samples > SampleCount::ONE) { if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE) { GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); @@ -614,6 +603,11 @@ void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) } } + if (gpuTexture->glTexture) { + gpuTexture->glTarget = GL_TEXTURE_EXTERNAL_OES; + return; + } + if (gpuTexture->glSamples <= 1) { #if CC_PLATFORM == CC_PLATFORM_WINDOWS // PVRVFrame issue gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); @@ -717,7 +711,9 @@ void cmdFuncGLES2DestroyTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture glTexture = 0; } } - GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->glTarget != GL_TEXTURE_EXTERNAL_OES) { + GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); + } gpuTexture->glTexture = 0; } else if (gpuTexture->glRenderbuffer) { @@ -732,7 +728,7 @@ void cmdFuncGLES2DestroyTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture } void cmdFuncGLES2ResizeTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - if (gpuTexture->memoryless) return; + if (gpuTexture->memoryless || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; if (gpuTexture->glSamples <= 1) { switch (gpuTexture->type) { @@ -1067,6 +1063,8 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { } // for // calculate offset & size + // WARNING: we can't handle inactive uniform arrays with wrong input sizes + // and there is no way to detect that for now for (auto &gpuBlock : gpuShader->glBlocks) { for (auto &gpuUniform : gpuBlock.glUniforms) { gpuUniform.offset = gpuBlock.size; @@ -1239,7 +1237,7 @@ void cmdFuncGLES2DestroyInputAssembler(GLES2Device *device, GLES2GPUInputAssembl } static GLuint doCreateFramebuffer(GLES2Device * device, - const vector &attachments, const uint *colors, uint colorCount, + const vector &attachments, const uint *colors, size_t colorCount, const GLES2GPUTexture *depthStencil, const uint * resolves = nullptr, const GLES2GPUTexture *depthStencilResolve = nullptr, @@ -1296,7 +1294,7 @@ static GLuint doCreateFramebuffer(GLES2Device * device, } if (device->hasFeature(Feature::MULTIPLE_RENDER_TARGETS)) { - GL_CHECK(glDrawBuffersEXT(drawBuffers.size(), drawBuffers.data())); + GL_CHECK(glDrawBuffersEXT(utils::toUint(drawBuffers.size()), drawBuffers.data())); } GLenum status; @@ -1324,38 +1322,55 @@ static GLuint doCreateFramebuffer(GLES2Device * device, return glFramebuffer; } +static GLES2GPUSwapchain *getSwapchainIfExists(const vector &textures, const uint32_t *indices, size_t count) { + GLES2GPUSwapchain *swapchain{nullptr}; + if (indices) { + size_t offscreenCount{0}; + for (size_t i = 0; i < count; ++i) { + auto *colorTexture = textures[indices[i]]; + if (colorTexture->swapchain) { + swapchain = colorTexture->swapchain; + } else { + ++offscreenCount; + } + } + CCASSERT(!offscreenCount || offscreenCount == count, "Partially offscreen FBO is not supported"); + } + return swapchain; +} + static void doCreateFramebufferInstance(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO, const vector &colors, - uint depthStencil, GLES2GPUFramebuffer::GLFramebuffer *outFBO, + uint depthStencil, GLES2GPUFramebuffer::Framebuffer *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"); + GLES2GPUSwapchain *swapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, colors.data(), colors.size())}; - 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 (!swapchain) { + 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); + outFBO->framebuffer.initialize(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); + size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + GLES2GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, resolves, resolveCount)}; + if (!resolveSwapchain) { + outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture)); + } else { + outFBO->resolveFramebuffer.initialize(resolveSwapchain); + } } } else { - outFBO->glFramebuffer = device->constantRegistry()->defaultFramebuffer; + outFBO->framebuffer.initialize(swapchain); } } @@ -1372,7 +1387,7 @@ void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpu if (GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].hasDepth) continue; gpuFBO->uberColorAttachmentIndices.push_back(i); } - doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); + doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, utils::toUint(gpuFBO->gpuColorTextures.size()), &gpuFBO->uberInstance); } else { for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), @@ -1381,35 +1396,30 @@ void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpu } } -static void doDestroyFramebuffer(GLES2GPUStateCache *cache, GLuint *pFBO) { - if (cache->glFramebuffer == *pFBO) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - cache->glFramebuffer = 0; +void GLES2GPUFramebuffer::GLFramebuffer::destroy(GLES2GPUStateCache *cache) { + if (swapchain) { + swapchain = nullptr; + } else { + if (cache->glFramebuffer == _glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); + cache->glFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, &_glFramebuffer)); + _glFramebuffer = 0U; } - GL_CHECK(glDeleteFramebuffers(1, pFBO)); - *pFBO = 0U; } void cmdFuncGLES2DestroyFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO) { - auto *cache = device->stateCache(); - uint defaultFBO = device->constantRegistry()->defaultFramebuffer; + auto *cache = device->stateCache(); for (auto &instance : gpuFBO->instances) { - if (instance.glFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &instance.glFramebuffer); - } - if (instance.glResolveFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &instance.glResolveFramebuffer); - } + instance.framebuffer.destroy(cache); + instance.resolveFramebuffer.destroy(cache); } gpuFBO->instances.clear(); - if (gpuFBO->uberInstance.glFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glFramebuffer); - } - if (gpuFBO->uberInstance.glResolveFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glResolveFramebuffer); - } + gpuFBO->uberInstance.framebuffer.destroy(cache); + gpuFBO->uberInstance.resolveFramebuffer.destroy(cache); } void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPURenderPass *gpuRenderPass, GLES2GPUFramebuffer *gpuFramebuffer, @@ -1439,9 +1449,13 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR if (gpuFramebuffer && gpuRenderPass) { const auto &instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[subpassIdx]; - if (cache->glFramebuffer != instance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, instance.glFramebuffer)); - cache->glFramebuffer = instance.glFramebuffer; + + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + device->context()->makeCurrent(instance.framebuffer.swapchain, instance.framebuffer.swapchain); + + if (cache->glFramebuffer != glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, glFramebuffer)); + cache->glFramebuffer = glFramebuffer; } if (cache->viewport.left != renderArea->x || @@ -1466,9 +1480,8 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR cache->scissor.height = renderArea->height; } - GLbitfield glClears = 0; - bool hasBoundFBO = instance.glFramebuffer; - bool maskSet = false; + GLbitfield glClears = 0; + bool maskSet = false; invalidAttachments.clear(); auto performLoadOp = [&](uint attachmentIndex, uint glAttachmentIndex) { @@ -1494,7 +1507,7 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } case LoadOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); break; } } @@ -1516,10 +1529,10 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); break; } - } // if (hasDepth) + } bool hasStencils = GFX_FORMAT_INFOS[static_cast(gpuRenderPass->depthStencilAttachment.format)].hasStencil; if (hasStencils) { switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { @@ -1536,13 +1549,13 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); break; } } if (!invalidAttachments.empty() && device->constantRegistry()->useDiscardFramebuffer) { - GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); } if (glClears) { @@ -1596,15 +1609,16 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR void cmdFuncGLES2EndRenderPass(GLES2Device *device) { static vector invalidAttachments; - 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; + 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; + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); + bool skipDiscard = false; invalidAttachments.clear(); auto performStoreOp = [&](uint attachmentIndex, uint glAttachmentIndex) { @@ -1614,7 +1628,7 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); break; } } @@ -1629,7 +1643,7 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); break; } } // if (hasDepth) @@ -1639,20 +1653,22 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); + invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); break; } } if (!skipDiscard && !invalidAttachments.empty() && device->constantRegistry()->useDiscardFramebuffer) { - GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); } }; if (instance.resolveMask) { - if (cache->glFramebuffer != instance.glResolveFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, instance.glResolveFramebuffer)); - cache->glFramebuffer = instance.glResolveFramebuffer; + device->context()->makeCurrent(instance.resolveFramebuffer.swapchain, instance.framebuffer.swapchain); + + if (cache->glFramebuffer != glResolveFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, glResolveFramebuffer)); + cache->glFramebuffer = glResolveFramebuffer; } TextureBlit region; @@ -2617,9 +2633,6 @@ CC_GLES2_API void cmdFuncGLES2CopyTextureToBuffers(GLES2Device *device, GLES2GPU } for (uint32_t i = 0; i < count; ++i) { auto region = regions[i]; - auto w = region.texExtent.width; - auto h = region.texExtent.height; - auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); uint8_t *copyDst = buffers[i]; GL_CHECK(glReadPixels(region.texOffset.x, region.texOffset.y, region.texExtent.width, region.texExtent.height, glFormat, glType, copyDst)); } @@ -2629,11 +2642,13 @@ void cmdFuncGLES2BlitTexture(GLES2Device *device, GLES2GPUTexture *gpuTextureSrc GLES2GPUStateCache *cache = device->stateCache(); GLuint dstFramebuffer = 0U; - if (gpuTextureDst) { - dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst); + if (gpuTextureDst->swapchain) { + dstFramebuffer = gpuTextureDst->swapchain->glFramebuffer; } else { - dstFramebuffer = device->constantRegistry()->defaultFramebuffer; + dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst); } + device->context()->makeCurrent(gpuTextureDst->swapchain, gpuTextureSrc->swapchain); + if (cache->glFramebuffer != dstFramebuffer) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, dstFramebuffer)); cache->glFramebuffer = dstFramebuffer; @@ -2802,6 +2817,30 @@ void GLES2GPUBlitManager::destroy() { cmdFuncGLES2DestroyShader(device, &_gpuShader); } +static void ensureScissorRect(GLES2GPUStateCache *cache, int32_t x, int32_t y, uint32_t width, uint32_t height) { + if (cache->viewport.left > x || + cache->viewport.top > y || + cache->viewport.width < width || + cache->viewport.height < height) { + cache->viewport.left = std::min(cache->viewport.left, x); + cache->viewport.top = std::min(cache->viewport.top, y); + cache->viewport.width = std::max(cache->viewport.width, width); + cache->viewport.height = std::max(cache->viewport.height, height); + GL_CHECK(glViewport(cache->viewport.left, cache->viewport.top, cache->viewport.width, cache->viewport.height)); + } + + if (cache->scissor.x > x || + cache->scissor.y > y || + cache->scissor.width < width || + cache->scissor.height < height) { + cache->scissor.x = std::min(cache->scissor.x, x); + cache->scissor.y = std::min(cache->scissor.y, y); + cache->scissor.width = std::max(cache->scissor.width, width); + cache->scissor.height = std::max(cache->scissor.height, height); + GL_CHECK(glScissor(cache->scissor.x, cache->scissor.y, cache->scissor.width, cache->scissor.height)); + } +} + void GLES2GPUBlitManager::draw(GLES2GPUTexture *gpuTextureSrc, GLES2GPUTexture *gpuTextureDst, const TextureBlit *regions, uint count, Filter filter) { GLES2GPUDescriptorSet *gpuDescriptorSet = &_gpuDescriptorSet; @@ -2813,10 +2852,10 @@ void GLES2GPUBlitManager::draw(GLES2GPUTexture *gpuTextureSrc, GLES2GPUTexture * for (uint i = 0U; i < count; ++i) { const auto ®ion = regions[i]; - auto srcWidth = static_cast(gpuTextureSrc ? gpuTextureSrc->width : device->getWidth()); - auto srcHeight = static_cast(gpuTextureSrc ? gpuTextureSrc->height : device->getHeight()); - auto dstWidth = static_cast(gpuTextureDst ? gpuTextureDst->width : device->getWidth()); - auto dstHeight = static_cast(gpuTextureDst ? gpuTextureDst->height : device->getHeight()); + auto srcWidth = static_cast(gpuTextureSrc->width); + auto srcHeight = static_cast(gpuTextureSrc->height); + auto dstWidth = static_cast(gpuTextureDst->width); + auto dstHeight = static_cast(gpuTextureDst->height); _uniformBuffer[0] = static_cast(region.srcExtent.width) / srcWidth; _uniformBuffer[1] = static_cast(region.srcExtent.height) / srcHeight; @@ -2827,6 +2866,8 @@ void GLES2GPUBlitManager::draw(GLES2GPUTexture *gpuTextureSrc, GLES2GPUTexture * _uniformBuffer[6] = static_cast(region.dstOffset.x) / dstWidth; _uniformBuffer[7] = static_cast(region.dstOffset.y) / dstHeight; + ensureScissorRect(device->stateCache(), region.dstOffset.x, region.dstOffset.y, region.dstExtent.width, region.dstExtent.height); + cmdFuncGLES2UpdateBuffer(device, &_gpuUniformBuffer, _uniformBuffer, 0, sizeof(_uniformBuffer)); cmdFuncGLES2BindState(device, &_gpuPipelineState, &_gpuInputAssembler, &gpuDescriptorSet); cmdFuncGLES2Draw(device, _drawInfo); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.h b/native/cocos/renderer/gfx-gles2/GLES2Commands.h index 77a02306b7..0f73fa0c87 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.h @@ -25,14 +25,19 @@ #pragma once -#include "gfx-gles-common/GLESCommandPool.h" - #include "GLES2GPUObjects.h" -#include "GLES2Std.h" namespace cc { namespace gfx { +#ifndef GL_COMPRESSED_RGB8_ETC2 + #define GL_COMPRESSED_RGB8_ETC2 0x9274 +#endif + +#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC + #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#endif + class GLES2Device; class GLES2CmdBeginRenderPass final : public GLESCmd { @@ -53,18 +58,6 @@ public: } }; -enum class GLES2State { - VIEWPORT, - SCISSOR, - LINE_WIDTH, - DEPTH_BIAS, - BLEND_CONSTANTS, - DEPTH_BOUNDS, - STENCIL_WRITE_MASK, - STENCIL_COMPARE_MASK, - COUNT, -}; - class GLES2CmdBindStates final : public GLESCmd { public: GLES2GPUPipelineState * gpuPipelineState = nullptr; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Context.cpp b/native/cocos/renderer/gfx-gles2/GLES2Context.cpp deleted file mode 100644 index e2e5df9880..0000000000 --- a/native/cocos/renderer/gfx-gles2/GLES2Context.cpp +++ /dev/null @@ -1,581 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES2Std.h" - -#include "GLES2Context.h" -#include "GLES2Device.h" -#include "GLES2GPUObjects.h" - -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) - #include "android/native_window.h" -#endif - -#define FORCE_DISABLE_VALIDATION 1 - -namespace cc { -namespace gfx { - -#if CC_DEBUG > 0 && defined(GL_DEBUG_SOURCE_API_KHR) - -void GL_APIENTRY GLES2EGLDebugProc(GLenum source, - GLenum type, GLuint id, - GLenum severity, GLsizei length, - const GLchar *message, - const void * userParam) { - String sourceDesc; - switch (source) { - case GL_DEBUG_SOURCE_API_KHR: sourceDesc = "API"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: sourceDesc = "SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR: sourceDesc = "WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY_KHR: sourceDesc = "THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION_KHR: sourceDesc = "APPLICATION"; break; - default: sourceDesc = "OTHER"; break; - } - - String typeDesc; - switch (type) { - case GL_DEBUG_TYPE_ERROR_KHR: typeDesc = "ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: typeDesc = "PEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: typeDesc = "UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PERFORMANCE_KHR: typeDesc = "PERFORMANCE"; break; - case GL_DEBUG_TYPE_PORTABILITY_KHR: typeDesc = "PORTABILITY"; break; - case GL_DEBUG_TYPE_MARKER_KHR: typeDesc = "MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP_KHR: typeDesc = "PUSH_GROUP"; break; - case GL_DEBUG_TYPE_POP_GROUP_KHR: typeDesc = "POP_GROUP"; break; - default: typeDesc = "OTHER"; break; - } - - String severityDesc; - switch (severity) { - case GL_DEBUG_SEVERITY_HIGH_KHR: severityDesc = "HIGH"; break; - case GL_DEBUG_SEVERITY_MEDIUM_KHR: severityDesc = "MEDIUM"; break; - case GL_DEBUG_SEVERITY_LOW_KHR: severityDesc = "LOW"; break; - default: severityDesc = "NOTIFICATION"; break; - } - - String msg = StringUtil::format("source: %s, type: %s, severity: %s, message: %s", - sourceDesc.c_str(), typeDesc.c_str(), severityDesc.c_str(), - message); - - if (severity == GL_DEBUG_SEVERITY_HIGH_KHR) { - CC_LOG_WARNING(msg.c_str()); - } else { - CC_LOG_DEBUG(msg.c_str()); - } -} - -#endif - -GLES2Context::GLES2Context() = default; - -GLES2Context::~GLES2Context() = default; - -#if (CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_OSX) - -bool GLES2Context::doInit(const ContextInfo &info) { - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; - auto *window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - - ////////////////////////////////////////////////////////////////////////// - - if (!info.sharedCtx) { - if (!gles2wInit()) { - return false; - } - - _isPrimaryContex = true; - _windowHandle = info.windowHandle; - - #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) - _nativeDisplay = GetDC(window); - if (!_nativeDisplay) { - return false; - } - - EGL_CHECK(_eglDisplay = eglGetDisplay(_nativeDisplay)); - if (_eglDisplay == EGL_NO_DISPLAY) { - EGL_CHECK(_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); - } - #else - EGL_CHECK(_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); - #endif - - // If a display still couldn't be obtained, return an error. - if (_eglDisplay == EGL_NO_DISPLAY) { - CC_LOG_ERROR("eglGetDisplay() - FAILED."); - return false; - } - - EGLint major = 0; - EGLint minor = 0; - if (eglInitialize(_eglDisplay, &major, &minor) != EGL_TRUE) { - CC_LOG_ERROR("Couldn't initialize EGLDisplay."); - return false; - } - - // Make OpenGL ES the current API. - // EGL needs a way to know that any subsequent EGL calls are going to be affecting OpenGL ES, - // rather than any other API (such as OpenVG). - EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API)); - - _colorFmt = Format::RGBA8; - _depthStencilFmt = Format::D24S8; - - bool msaaEnabled = info.msaaEnabled; - EGLint redSize{8}; - EGLint greenSize{8}; - EGLint blueSize{8}; - EGLint alphaSize{8}; - EGLint depthSize{24}; - EGLint stencilSize{8}; - EGLint sampleBufferSize{msaaEnabled ? EGL_DONT_CARE : 0}; - EGLint sampleSize{msaaEnabled ? EGL_DONT_CARE : 0}; - - EGLint defaultAttribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - // EGL_BUFFER_SIZE, colorBuffSize, - EGL_BLUE_SIZE, blueSize, - EGL_GREEN_SIZE, greenSize, - EGL_RED_SIZE, redSize, - EGL_ALPHA_SIZE, alphaSize, - EGL_DEPTH_SIZE, depthSize, - EGL_STENCIL_SIZE, stencilSize, - EGL_SAMPLE_BUFFERS, sampleBufferSize, - EGL_SAMPLES, sampleSize, - EGL_NONE}; - - int numConfig = 0; - - EGLConfig cfgs[128]; - - eglGetConfigs(_eglDisplay, cfgs, 128, &numConfig); - if (eglChooseConfig(_eglDisplay, defaultAttribs, nullptr, 0, &numConfig)) { - _vecEGLConfig.resize(numConfig); - } else { - CC_LOG_ERROR("Query configuration failed."); - return false; - } - - int count = numConfig; - if (eglChooseConfig(_eglDisplay, defaultAttribs, _vecEGLConfig.data(), count, &numConfig) == EGL_FALSE || !numConfig) { - CC_LOG_ERROR("eglChooseConfig configuration failed."); - return false; - } - - EGLint depth{0}; - EGLint stencil{0}; - const uint8_t attrNums = 8; - EGLint params[attrNums] = {0}; - bool matched = false; - const bool qualityPreferred = info.performance == Performance::HIGH_QUALITY; - uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); - - for (int i = 0; i < numConfig; i++) { - int depthValue{0}; - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_RED_SIZE, ¶ms[0]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_GREEN_SIZE, ¶ms[1]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_BLUE_SIZE, ¶ms[2]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_ALPHA_SIZE, ¶ms[3]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_DEPTH_SIZE, ¶ms[4]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_STENCIL_SIZE, ¶ms[5]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_SAMPLE_BUFFERS, ¶ms[6]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_SAMPLES, ¶ms[7]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_DEPTH_ENCODING_NV, &depthValue); - - int bNonLinearDepth = (depthValue == EGL_DEPTH_ENCODING_NONLINEAR_NV) ? 1 : 0; - - /*------------------------------------------ANGLE's priority-----------------------------------------------*/ - // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha - uint64_t currScore{0}; - EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); - currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; - currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; - currScore |= static_cast(std::min(colorScore, 127)) << 17; - currScore |= static_cast(std::min(std::abs(params[4] - depthSize), 63)) << 11; - currScore |= static_cast(std::min(std::abs(1 - bNonLinearDepth), 1)) << 10; - currScore |= static_cast(std::min(std::abs(params[5] - stencilSize), 31)) << 6; - currScore |= static_cast(std::min(std::abs(params[3] - alphaSize), 31)) << 0; - /*------------------------------------------ANGLE's priority-----------------------------------------------*/ - - // if msaaEnabled, sampleBuffers and sampleCount should be greater than 0, until iterate to the last one(can't find). - bool msaaLimit = (msaaEnabled ? (params[6] > 0 && params[7] > 0) : (params[6] == 0 && params[7] == 0)); - // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" - bool filter = (currScore < lastScore) ^ qualityPreferred; - if ((filter && msaaLimit) || (!matched && i == numConfig - 1)) { - _eglConfig = _vecEGLConfig[i]; - depth = params[4]; - stencil = params[5]; - _sampleBuffers = static_cast(params[6]); - _sampleCount = static_cast(params[7]); - lastScore = currScore; - matched = true; - } - } - - // Find a suitable EGLConfig - // eglChooseConfig is provided by EGL to provide an easy way to select an appropriate configuration. It takes in the capabilities - // specified in the attribute list, and returns a list of available configurations that match or exceed the capabilities requested. - // Details of all the possible attributes and how they are selected for by this function are available in the EGL reference pages here: - // http://www.khronos.org/registry/egl/sdk/docs/man/xhtml/eglChooseConfig.html - // It is also possible to simply get the entire list of configurations and use a custom algorithm to choose a suitable one, as many - // advanced applications choose to do. For this application however, taking the first EGLConfig that the function returns suits - // its needs perfectly, so we limit it to returning a single EGLConfig. - - CC_LOG_INFO("Setup EGLConfig: depth [%d] stencil [%d] sampleBuffer [%d] sampleCount [%d]", depth, stencil, _sampleBuffers, _sampleCount); - - if (depth == 16 && stencil == 0) { - _depthStencilFmt = Format::D16; - } else if (depth == 16 && stencil == 8) { - _depthStencilFmt = Format::D16S8; - } else if (depth == 24 && stencil == 0) { - _depthStencilFmt = Format::D24; - } else if (depth == 24 && stencil == 8) { - _depthStencilFmt = Format::D24S8; - } else if (depth == 32 && stencil == 0) { - _depthStencilFmt = Format::D32F; - } else if (depth == 32 && stencil == 8) { - _depthStencilFmt = Format::D32F_S8; - } else { - CC_LOG_ERROR("Unknown depth stencil format."); - return false; - } - - CC_LOG_INFO("Chosen EGLConfig: color [%s], depth stencil [%s].", - GFX_FORMAT_INFOS[static_cast(_colorFmt)].name.c_str(), - GFX_FORMAT_INFOS[static_cast(_depthStencilFmt)].name.c_str()); - - /** - * EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is - * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). - * As soon as we picked a EGLConfig, we can safely reconfigure the - * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. - */ - - #if (CC_PLATFORM == CC_PLATFORM_ANDROID) - EGLint nFmt = 0; - - if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { - CC_LOG_ERROR("Getting configuration attributes failed."); - return false; - } - - auto width = static_cast(GLES2Device::getInstance()->getWidth()); - auto height = static_cast(GLES2Device::getInstance()->getHeight()); - - ANativeWindow_setBuffersGeometry(window, width, height, nFmt); - #endif - - EGL_CHECK(_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, window, nullptr)); - if (_eglSurface == EGL_NO_SURFACE) { - CC_LOG_ERROR("Window surface created failed."); - return false; - } - - EGL_CHECK(_extensions = StringUtil::split(eglQueryString(_eglDisplay, EGL_EXTENSIONS), " ")); - - _majorVersion = 2; - _minorVersion = 0; - EGLint ctxAttribs[32]; - uint n = 0; - - bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); - if (hasKHRCreateCtx) { - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION - ctxAttribs[n++] = EGL_CONTEXT_FLAGS_KHR; - ctxAttribs[n++] = EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - #endif - ctxAttribs[n++] = EGL_CONTEXT_MAJOR_VERSION_KHR; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n++] = EGL_CONTEXT_MINOR_VERSION_KHR; - ctxAttribs[n++] = _minorVersion; - ctxAttribs[n] = EGL_NONE; - } else { - ctxAttribs[n++] = EGL_CONTEXT_CLIENT_VERSION; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n] = EGL_NONE; - } - - EGL_CHECK(_eglContext = eglCreateContext(_eglDisplay, _eglConfig, nullptr, ctxAttribs)); - if (!_eglContext) { - CC_LOG_ERROR("Create EGL context failed."); - return false; - } - - _eglSharedContext = _eglContext; - } else { - auto *sharedCtx = static_cast(info.sharedCtx); - - _majorVersion = sharedCtx->majorVer(); - _minorVersion = sharedCtx->minorVer(); - _nativeDisplay = sharedCtx->nativeDisplay(); - _eglDisplay = sharedCtx->eglDisplay(); - _eglConfig = sharedCtx->eglConfig(); - _eglSharedContext = sharedCtx->eglSharedCtx(); - _eglSurface = sharedCtx->eglSurface(); - _colorFmt = sharedCtx->getColorFormat(); - _depthStencilFmt = sharedCtx->getDepthStencilFormat(); - _majorVersion = sharedCtx->majorVer(); - _minorVersion = sharedCtx->minorVer(); - _extensions = sharedCtx->_extensions; - _isInitialized = sharedCtx->_isInitialized; - - bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); - if (!hasKHRCreateCtx) { - CC_LOG_INFO( - "EGL context creation: EGL_KHR_create_context not supported. Minor version will be discarded, and debug disabled."); - _minorVersion = 0; - } - - EGLint ctxAttribs[32]; - uint n = 0; - - if (hasKHRCreateCtx) { - ctxAttribs[n++] = EGL_CONTEXT_MAJOR_VERSION_KHR; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n++] = EGL_CONTEXT_MINOR_VERSION_KHR; - ctxAttribs[n++] = _minorVersion; - - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION - ctxAttribs[n++] = EGL_CONTEXT_FLAGS_KHR; - ctxAttribs[n++] = EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - #endif - } else { - ctxAttribs[n++] = EGL_CONTEXT_CLIENT_VERSION; - ctxAttribs[n++] = _majorVersion; - } - - ctxAttribs[n] = EGL_NONE; - - EGL_CHECK(_eglContext = eglCreateContext(_eglDisplay, _eglConfig, _eglSharedContext, ctxAttribs)); - if (!_eglContext) { - CC_LOG_ERROR("Create EGL context with share context [0x%p] failed.", _eglSharedContext); - return false; - } - } - - return true; -} - -void GLES2Context::doDestroy() { - if (_eglDisplay) { - EGL_CHECK(eglMakeCurrent(_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - } - - if (!_vecEGLConfig.empty()) { - _vecEGLConfig.clear(); - } - - if (_eglContext != EGL_NO_CONTEXT) { - EGL_CHECK(eglDestroyContext(_eglDisplay, _eglContext)); - _eglContext = EGL_NO_CONTEXT; - } - - if (_isPrimaryContex) { - if (_eglSurface != EGL_NO_SURFACE) { - EGL_CHECK(eglDestroySurface(_eglDisplay, _eglSurface)); - _eglSurface = EGL_NO_SURFACE; - } - - if (_eglDisplay != EGL_NO_DISPLAY) { - EGL_CHECK(eglTerminate(_eglDisplay)); - _eglDisplay = EGL_NO_DISPLAY; - } - - #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) - if (_nativeDisplay) { - ReleaseDC(reinterpret_cast(_windowHandle), _nativeDisplay); - } - #endif - } - - _isPrimaryContex = false; - _windowHandle = 0; - _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues - _vsyncMode = VsyncMode::OFF; - _isInitialized = false; -} - -void GLES2Context::releaseSurface(uintptr_t /*windowHandle*/) { - #if (CC_PLATFORM == CC_PLATFORM_ANDROID) - if (_eglSurface != EGL_NO_SURFACE) { - eglDestroySurface(_eglDisplay, _eglSurface); - _eglSurface = EGL_NO_SURFACE; - } - #endif -} - -void GLES2Context::acquireSurface(uintptr_t windowHandle) { - #if (CC_PLATFORM == CC_PLATFORM_ANDROID) - { - _windowHandle = windowHandle; - auto *window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - - EGLint nFmt = 0; - if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { - CC_LOG_ERROR("Getting configuration attributes failed."); - return; - } - - // Device's size will be updated after recreate window (in resize event) and is incorrect for now. - int32_t width = ANativeWindow_getWidth(window); - int32_t height = ANativeWindow_getHeight(window); - ANativeWindow_setBuffersGeometry(window, width, height, nFmt); - GLES2Device::getInstance()->resize(width, height); - - EGL_CHECK(_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, window, nullptr)); - if (_eglSurface == EGL_NO_SURFACE) { - CC_LOG_ERROR("Recreate window surface failed."); - return; - } - - static_cast(GLES2Device::getInstance()->getContext())->makeCurrent(); - GLES2Device::getInstance()->stateCache()->reset(); - } - #endif -} - -bool GLES2Context::makeCurrentImpl(bool bound) { - bool succeeded; - EGL_CHECK(succeeded = eglMakeCurrent(_eglDisplay, - bound ? _eglSurface : EGL_NO_SURFACE, - bound ? _eglSurface : EGL_NO_SURFACE, - bound ? _eglContext : EGL_NO_CONTEXT)); - return succeeded; -} - -void GLES2Context::present() { - EGL_CHECK(eglSwapBuffers(_eglDisplay, _eglSurface)); -} - -#endif - -bool GLES2Context::makeCurrent(bool bound) { - if (!bound) { - CC_LOG_DEBUG("eglMakeCurrent() - UNBOUNDED, Context: 0x%p", this); - return makeCurrentImpl(false); - } - - if (makeCurrentImpl(bound)) { -#if (CC_PLATFORM != CC_PLATFORM_MAC_IOS) - if (!_isInitialized) { - // Turn on or off the vertical sync depending on the input bool value. - int interval = 1; - switch (_vsyncMode) { - case VsyncMode::OFF: interval = 0; break; - case VsyncMode::ON: - case VsyncMode::RELAXED: interval = 1; break; - case VsyncMode::MAILBOX: interval = 0; break; - case VsyncMode::HALF: interval = 2; break; - default: break; - } - - if (eglSwapInterval(_eglDisplay, interval) != 1) { - CC_LOG_ERROR("wglSwapInterval() - FAILED."); - return false; - } - _isInitialized = true; - } - - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION && defined(GL_DEBUG_SOURCE_API_KHR) - GL_CHECK(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR)); - if (glDebugMessageControlKHR) { - GL_CHECK(glDebugMessageControlKHR(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE)); - } - if (glDebugMessageCallbackKHR) { - GL_CHECK(glDebugMessageCallbackKHR(GLES2EGLDebugProc, NULL)); - } - #endif - -#endif - - ////////////////////////////////////////////////////////////////////////// - - GL_CHECK(glPixelStorei(GL_PACK_ALIGNMENT, 1)); - GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - GL_CHECK(glActiveTexture(GL_TEXTURE0)); - - ////////////////////////////////////////////////////////////////////////// - - GL_CHECK(glEnable(GL_SCISSOR_TEST)); - GL_CHECK(glEnable(GL_CULL_FACE)); - GL_CHECK(glCullFace(GL_BACK)); - - GL_CHECK(glFrontFace(GL_CCW)); - - //GL_CHECK(glDisable(GL_MULTISAMPLE)); - - ////////////////////////////////////////////////////////////////////////// - // DepthStencilState - GL_CHECK(glEnable(GL_DEPTH_TEST)); - GL_CHECK(glDepthMask(GL_TRUE)); - GL_CHECK(glDepthFunc(GL_LESS)); - - GL_CHECK(glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xffffffff)); - GL_CHECK(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP)); - GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); - GL_CHECK(glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 1, 0xffffffff)); - GL_CHECK(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP)); - GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); - - GL_CHECK(glDisable(GL_STENCIL_TEST)); - - ////////////////////////////////////////////////////////////////////////// - // BlendState - - GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE)); - GL_CHECK(glDisable(GL_BLEND)); - GL_CHECK(glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD)); - GL_CHECK(glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO)); - GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); - GL_CHECK(glBlendColor(0.0F, 0.0F, 0.0F, 0.0F)); - - GL_CHECK(glUseProgram(0)); - - GL_CHECK(glBindVertexArrayOES(0)); - - GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); - - GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); - - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - - CC_LOG_DEBUG("eglMakeCurrent() - SUCCEEDED, Context: 0x%p", this); - return true; - } - CC_LOG_ERROR("MakeCurrent() - FAILED, Context: 0x%p", this); - return false; -} - -bool GLES2Context::checkExtension(const String &extension) const { - return (std::find(_extensions.begin(), _extensions.end(), extension) != _extensions.end()); -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Context.h b/native/cocos/renderer/gfx-gles2/GLES2Context.h deleted file mode 100644 index a9dc666e50..0000000000 --- a/native/cocos/renderer/gfx-gles2/GLES2Context.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include -#include "GLES2Std.h" -#include "GLES2Wrangler.h" -#include "gfx-base/GFXContext.h" - -namespace cc { -namespace gfx { - -class CC_GLES2_API GLES2Context final : public Context { -public: - GLES2Context(); - ~GLES2Context() override; - - void present() override; - bool makeCurrent(bool bound); - - bool checkExtension(const String &extension) const; - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - inline intptr_t eagl_context() const { return _eaglContext; } - inline intptr_t eagl_shared_ctx() const { return _eaglSharedContext; } -#else - inline NativeDisplayType nativeDisplay() const { return _nativeDisplay; } - inline EGLDisplay eglDisplay() const { return _eglDisplay; } - inline EGLConfig eglConfig() const { return _eglConfig; } - inline EGLSurface eglSurface() const { return _eglSurface; } - inline EGLContext eglContext() const { return _eglContext; } - inline EGLContext eglSharedCtx() const { return _eglSharedContext; } -#endif - inline bool makeCurrent() { return makeCurrent(true); } - 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); - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - bool createCustomFrameBuffer(); - void doDestroyCustomFrameBuffer(); -#endif - - void releaseSurface(uintptr_t windowHandle); - void acquireSurface(uintptr_t windowHandle); - -protected: - bool doInit(const ContextInfo &info) override; - void doDestroy() override; - - bool _isPrimaryContex = false; - 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 _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; -#endif - int _majorVersion = 0; - int _minorVersion = 0; - StringArray _extensions; -}; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Context.mm b/native/cocos/renderer/gfx-gles2/GLES2Context.mm deleted file mode 100644 index e487f9dd6d..0000000000 --- a/native/cocos/renderer/gfx-gles2/GLES2Context.mm +++ /dev/null @@ -1,223 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES2Std.h" -#include "GLES2Context.h" - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - -#import - -namespace cc { -namespace gfx { - -bool GLES2Context::doInit(const ContextInfo &info) { - - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; - - ////////////////////////////////////////////////////////////////////////// - - if (!info.sharedCtx) { - _isPrimaryContex = true; - _windowHandle = info.windowHandle; - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)( ((UIView*)(_windowHandle)).layer); - eaglLayer.opaque = TRUE; - - EAGLContext* eagl_context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2]; - if (!eagl_context) { - CC_LOG_ERROR("Create EAGL context failed."); - return false; - } - - _eaglContext = (intptr_t)eagl_context; - _eaglSharedContext = (intptr_t)eagl_context; - - if (!gles2wInit()) - return false; - } else { - GLES2Context* sharedCtx = (GLES2Context*)info.sharedCtx; - _majorVersion = sharedCtx->_majorVersion; - _defaultFBO = sharedCtx->_defaultFBO; - _defaultColorBuffer = sharedCtx->_defaultColorBuffer; - _defaultDepthStencilBuffer = sharedCtx->_defaultDepthStencilBuffer; - - EAGLContext* eagl_shared_context = (EAGLContext*)sharedCtx->eagl_shared_ctx(); - EAGLContext* eagl_context = [[EAGLContext alloc] initWithAPI: [eagl_shared_context API] sharegroup: [eagl_shared_context sharegroup]]; - if (!eagl_context) { - CC_LOG_ERROR("Create EGL context with share context [0x%p] failed.", eagl_shared_context); - return false; - } - - _eaglContext = (intptr_t)eagl_context; - _eaglSharedContext = (intptr_t)eagl_shared_context; - } - - _colorFmt = Format::RGBA8; - _depthStencilFmt = Format::D24S8; - - return true; -} - -bool GLES2Context::createCustomFrameBuffer() { - if (_defaultFBO) { - glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO); - glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer); - return true; - } - - glGenFramebuffers(1, &_defaultFBO); - if (0 == _defaultFBO) { - CC_LOG_ERROR("Can not create default frame buffer"); - return false; - } - glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO); - - glGenRenderbuffers(1, &_defaultColorBuffer); - if (0 == _defaultColorBuffer) { - CC_LOG_ERROR("Can not create default color buffer"); - return false; - } - glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer); - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)( ((UIView*)(_windowHandle)).layer); - - //get the storage from iOS so it can be displayed in the view - if (! [(EAGLContext*)_eaglContext renderbufferStorage:GL_RENDERBUFFER - fromDrawable:eaglLayer]) { - CC_LOG_ERROR("Attaches EAGLDrawable as storage for the OpenGL ES renderbuffer object failed."); - glBindRenderbuffer(GL_RENDERBUFFER, 0); - glDeleteRenderbuffers(1, &_defaultColorBuffer); - return false; - } - - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _defaultColorBuffer); - - //get the frame's width and height - GLint framebufferWidth = 0, framebufferHeight = 0; - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth); - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight); - glGenRenderbuffers(1, &_defaultDepthStencilBuffer); - if (_defaultDepthStencilBuffer == 0) - { - // Application can run without depth/stencil buffer, so don't return false here. - CC_LOG_ERROR("Can not create default depth/stencil buffer"); - } - glBindRenderbuffer(GL_RENDERBUFFER, _defaultDepthStencilBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, framebufferWidth, framebufferHeight); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthStencilBuffer); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthStencilBuffer); - - 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; - } - default:; - } - doDestroyCustomFrameBuffer(); - return false; - } - - glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer); - return true; -} - -void GLES2Context::doDestroyCustomFrameBuffer() -{ - if (_defaultColorBuffer) - { - glDeleteRenderbuffers(1, &_defaultColorBuffer); - _defaultColorBuffer = 0; - } - if (_defaultDepthStencilBuffer) - { - glDeleteRenderbuffers(1, &_defaultDepthStencilBuffer); - _defaultDepthStencilBuffer = 0; - } - - if (_defaultFBO) - { - glDeleteFramebuffers(1, &_defaultFBO); - _defaultFBO = 0; - } -} - -void GLES2Context::doDestroy() { - doDestroyCustomFrameBuffer(); - - if (_eaglContext) { - [(EAGLContext*)_eaglContext release]; - } - - _isPrimaryContex = false; - _windowHandle = 0; - _vsyncMode = VsyncMode::OFF; - _isInitialized = false; -} - -void GLES2Context::present() { - if (! [(EAGLContext*)_eaglContext presentRenderbuffer:GL_RENDERBUFFER] ) - { - CC_LOG_ERROR("Failed to present content."); - } -} - -bool GLES2Context::makeCurrentImpl(bool bound) { - if (!bound) return [EAGLContext setCurrentContext: nil]; - return [EAGLContext setCurrentContext: (EAGLContext*)_eaglContext] && createCustomFrameBuffer(); -} - -void GLES2Context::releaseSurface(uintptr_t /*windowHandle*/) { -} - -void GLES2Context::acquireSurface(uintptr_t /*windowHandle*/) { -} - -} // namespace gfx -} // namespace cc - -#endif diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp index 22a39574f5..45ee26103d 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp @@ -29,8 +29,8 @@ #include "GLES2Commands.h" #include "GLES2DescriptorSet.h" #include "GLES2DescriptorSetLayout.h" -#include "GLES2Sampler.h" #include "GLES2Texture.h" +#include "states/GLES2Sampler.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.h b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.h index 1a0379ce09..bf9e19bfd3 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.h +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES2_DESCRIPTOR_SET_H_ -#define CC_GFXGLES2_DESCRIPTOR_SET_H_ +#pragma once +#include "GLES2Std.h" #include "gfx-base/GFXDescriptorSet.h" namespace cc { @@ -36,7 +36,7 @@ class GLES2GPUDescriptorSet; class CC_GLES2_API GLES2DescriptorSet final : public DescriptorSet { public: GLES2DescriptorSet(); - ~GLES2DescriptorSet(); + ~GLES2DescriptorSet() override; void update() override; @@ -51,5 +51,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES2_DESCRIPTOR_SET_H_ diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.h b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.h index 49cadbba5d..709211c1eb 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES2_DESCRIPTOR_SET_LAYOUT_H_ -#define CC_GFXGLES2_DESCRIPTOR_SET_LAYOUT_H_ +#pragma once +#include "GLES2Std.h" #include "gfx-base/GFXDescriptorSetLayout.h" namespace cc { @@ -36,7 +36,7 @@ class GLES2GPUDescriptorSetLayout; class CC_GLES2_API GLES2DescriptorSetLayout final : public DescriptorSetLayout { public: GLES2DescriptorSetLayout(); - ~GLES2DescriptorSetLayout(); + ~GLES2DescriptorSetLayout() override; inline GLES2GPUDescriptorSetLayout *gpuDescriptorSetLayout() const { return _gpuDescriptorSetLayout; } @@ -49,5 +49,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES2_DESCRIPTOR_SET_LAYOUT_H_ diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 643ae85317..89b5749a00 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -27,20 +27,22 @@ #include "GLES2Buffer.h" #include "GLES2CommandBuffer.h" -#include "GLES2Context.h" +#include "GLES2Commands.h" #include "GLES2DescriptorSet.h" #include "GLES2DescriptorSetLayout.h" #include "GLES2Device.h" #include "GLES2Framebuffer.h" +#include "GLES2GPUObjects.h" #include "GLES2InputAssembler.h" #include "GLES2PipelineLayout.h" #include "GLES2PipelineState.h" #include "GLES2PrimaryCommandBuffer.h" #include "GLES2Queue.h" #include "GLES2RenderPass.h" -#include "GLES2Sampler.h" #include "GLES2Shader.h" +#include "GLES2Swapchain.h" #include "GLES2Texture.h" +#include "states/GLES2Sampler.h" // when capturing GLES commands (RENDERDOC_HOOK_EGL=1, default value) // renderdoc doesn't support this extension during replay @@ -66,17 +68,17 @@ GLES2Device::~GLES2Device() { GLES2Device::instance = nullptr; } -bool GLES2Device::doInit(const DeviceInfo &info) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - ctxInfo.msaaEnabled = info.isAntiAlias; - ctxInfo.performance = Performance::HIGH_QUALITY; +bool GLES2Device::doInit(const DeviceInfo & /*info*/) { + _gpuContext = CC_NEW(GLES2GPUContext); + _gpuStateCache = CC_NEW(GLES2GPUStateCache); + _gpuBlitManager = CC_NEW(GLES2GPUBlitManager); + _gpuConstantRegistry = CC_NEW(GLES2GPUConstantRegistry); + _gpuFramebufferCacheMap = CC_NEW(GLES2GPUFramebufferCacheMap(_gpuStateCache)); - _renderContext = CC_NEW(GLES2Context); - if (!_renderContext->initialize(ctxInfo)) { + if (!_gpuContext->initialize(_gpuStateCache, _gpuConstantRegistry)) { destroy(); return false; - } + }; QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; @@ -87,14 +89,6 @@ bool GLES2Device::doInit(const DeviceInfo &info) { cmdBuffInfo.queue = _queue; _cmdBuff = createCommandBuffer(cmdBuffInfo); - _gpuStateCache = CC_NEW(GLES2GPUStateCache); - _gpuBlitManager = CC_NEW(GLES2GPUBlitManager); - _gpuStagingBufferPool = CC_NEW(GLES2GPUStagingBufferPool); - _gpuConstantRegistry = CC_NEW(GLES2GPUConstantRegistry); - _gpuFramebufferCacheMap = CC_NEW(GLES2GPUFramebufferCacheMap(_gpuStateCache)); - - bindRenderContext(true); - String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); @@ -150,17 +144,9 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _features[toNumber(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"; + // PVRVFrame has issues on their support +#if CC_PLATFORM != CC_PLATFORM_WINDOWS if (checkExtension("framebuffer_fetch")) { String nonCoherent = "framebuffer_fetch_non"; @@ -183,6 +169,17 @@ bool GLES2Device::doInit(const DeviceInfo &info) { fbfLevelStr = "COHERENT"; } } +#endif + +#if CC_PLATFORM != CC_PLATFORM_WINDOWS || 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 compressedFmts; @@ -211,16 +208,6 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _vendor = reinterpret_cast(glGetString(GL_VENDOR)); _version = reinterpret_cast(glGetString(GL_VERSION)); - CC_LOG_INFO("GLES2 device initialized."); - CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); - CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); - 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", _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)); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxFragmentUniformVectors)); @@ -228,12 +215,18 @@ bool GLES2Device::doInit(const DeviceInfo &info) { glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, reinterpret_cast(&_caps.maxVertexTextureUnits)); glGetIntegerv(GL_MAX_TEXTURE_SIZE, reinterpret_cast(&_caps.maxTextureSize)); glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, reinterpret_cast(&_caps.maxCubeMapTextureSize)); - glGetIntegerv(GL_DEPTH_BITS, reinterpret_cast(&_caps.depthBits)); - glGetIntegerv(GL_STENCIL_BITS, reinterpret_cast(&_caps.stencilBits)); _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxVertexAttributes); _gpuBlitManager->initialize(); + CC_LOG_INFO("GLES2 device initialized."); + CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); + CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); + CC_LOG_INFO("VERSION: %s", _version.c_str()); + CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); + CC_LOG_INFO("USE_VAO: %s", _gpuConstantRegistry->useVAO ? "true" : "false"); + CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + return true; } @@ -242,7 +235,6 @@ void GLES2Device::doDestroy() { CC_SAFE_DELETE(_gpuFramebufferCacheMap) CC_SAFE_DELETE(_gpuConstantRegistry) - CC_SAFE_DELETE(_gpuStagingBufferPool) CC_SAFE_DELETE(_gpuBlitManager) CC_SAFE_DELETE(_gpuStateCache) @@ -251,25 +243,14 @@ void GLES2Device::doDestroy() { CC_SAFE_DESTROY(_cmdBuff) CC_SAFE_DESTROY(_queue) - CC_SAFE_DESTROY(_deviceContext) - CC_SAFE_DESTROY(_renderContext) + CC_SAFE_DESTROY(_gpuContext) } -void GLES2Device::releaseSurface(uintptr_t windowHandle) { - static_cast(_context)->releaseSurface(windowHandle); -} - -void GLES2Device::acquireSurface(uintptr_t windowHandle) { - static_cast(_context)->acquireSurface(windowHandle); -} - -void GLES2Device::resize(uint width, uint height) { - _width = width; - _height = height; -} - -void GLES2Device::acquire() { - _gpuStagingBufferPool->reset(); +void GLES2Device::acquire(Swapchain *const *swapchains, uint32_t count) { + _swapchains.clear(); + for (uint32_t i = 0; i < count; ++i) { + _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); + } } void GLES2Device::present() { @@ -278,7 +259,9 @@ void GLES2Device::present() { _numInstances = queue->_numInstances; _numTriangles = queue->_numTriangles; - _context->present(); + for (auto *swapchain : _swapchains) { + _gpuContext->present(swapchain); + } // Clear queue stats queue->_numDrawCalls = 0; @@ -286,32 +269,8 @@ void GLES2Device::present() { queue->_numTriangles = 0; } -void GLES2Device::bindRenderContext(bool bound) { - _renderContext->makeCurrent(bound); - _context = bound ? _renderContext : nullptr; - - if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); - _gpuStateCache->reset(); - } -} - -void GLES2Device::bindDeviceContext(bool bound) { - if (!_deviceContext) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - ctxInfo.sharedCtx = _renderContext; - - _deviceContext = CC_NEW(GLES2Context); - _deviceContext->initialize(ctxInfo); - } - _deviceContext->makeCurrent(bound); - _context = bound ? _deviceContext : nullptr; - - if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); - _gpuStateCache->reset(); - } +void GLES2Device::bindContext(bool bound) { + _gpuContext->bindContext(bound); } CommandBuffer *GLES2Device::createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) { @@ -323,6 +282,10 @@ Queue *GLES2Device::createQueue() { return CC_NEW(GLES2Queue); } +Swapchain *GLES2Device::createSwapchain() { + return CC_NEW(GLES2Swapchain); +} + Buffer *GLES2Device::createBuffer() { return CC_NEW(GLES2Buffer); } @@ -331,10 +294,6 @@ Texture *GLES2Device::createTexture() { return CC_NEW(GLES2Texture); } -Sampler *GLES2Device::createSampler() { - return CC_NEW(GLES2Sampler); -} - Shader *GLES2Device::createShader() { return CC_NEW(GLES2Shader); } @@ -367,12 +326,16 @@ PipelineState *GLES2Device::createPipelineState() { return CC_NEW(GLES2PipelineState); } -GlobalBarrier *GLES2Device::createGlobalBarrier() { - return CC_NEW(GlobalBarrier); +Sampler *GLES2Device::createSampler(const SamplerInfo &info) { + return CC_NEW(GLES2Sampler(info)); } -TextureBarrier *GLES2Device::createTextureBarrier() { - return CC_NEW(TextureBarrier); +GlobalBarrier *GLES2Device::createGlobalBarrier(const GlobalBarrierInfo &info) { + return CC_NEW(GlobalBarrier(info)); +} + +TextureBarrier *GLES2Device::createTextureBarrier(const TextureBarrierInfo &info) { + return CC_NEW(TextureBarrier(info)); } void GLES2Device::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { @@ -386,8 +349,8 @@ void GLES2Device::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, co bool GLES2Device::checkForETC2() { GLint numFormats = 0; glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numFormats); - auto *formats = new GLint[numFormats]; - glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats); + vector formats(numFormats); + glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats.data()); int supportNum = 0; for (GLint i = 0; i < numFormats; ++i) { @@ -395,8 +358,6 @@ bool GLES2Device::checkForETC2() { supportNum++; } } - delete[] formats; - return supportNum >= 2; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 398457b1fd..3279ff8f9f 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -26,24 +26,16 @@ #pragma once #include "GLES2Std.h" - #include "gfx-base/GFXDevice.h" - -#ifndef GL_COMPRESSED_RGB8_ETC2 - #define GL_COMPRESSED_RGB8_ETC2 0x9274 -#endif - -#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC - #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#endif +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { -class GLES2Context; +class GLES2GPUContext; +class GLES2GPUSwapchain; class GLES2GPUStateCache; class GLES2GPUBlitManager; -class GLES2GPUStagingBufferPool; class GLES2GPUConstantRegistry; class GLES2GPUFramebufferCacheMap; @@ -70,13 +62,12 @@ public: using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; + inline GLES2GPUContext * context() const { return _gpuContext; } inline GLES2GPUStateCache * stateCache() const { return _gpuStateCache; } inline GLES2GPUBlitManager * blitManager() const { return _gpuBlitManager; } - inline GLES2GPUStagingBufferPool * stagingBufferPool() const { return _gpuStagingBufferPool; } inline GLES2GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } inline GLES2GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } @@ -90,7 +81,6 @@ protected: static GLES2Device *instance; friend class DeviceManager; - friend class GLES2Context; GLES2Device(); @@ -98,9 +88,9 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -109,26 +99,25 @@ protected: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture* src, uint8_t *const* buffers, const BufferTextureCopy* region, uint count) override; - void releaseSurface(uintptr_t windowHandle) override; - void acquireSurface(uintptr_t windowHandle) override; + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; - void bindRenderContext(bool bound) override; - void bindDeviceContext(bool bound) override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + + void bindContext(bool bound) override; static bool checkForETC2(); - GLES2Context * _renderContext = nullptr; - GLES2Context * _deviceContext = nullptr; - GLES2GPUStateCache * _gpuStateCache = nullptr; - GLES2GPUBlitManager * _gpuBlitManager = nullptr; - GLES2GPUStagingBufferPool * _gpuStagingBufferPool = nullptr; - GLES2GPUConstantRegistry * _gpuConstantRegistry = nullptr; - GLES2GPUFramebufferCacheMap *_gpuFramebufferCacheMap = nullptr; + GLES2GPUContext * _gpuContext{nullptr}; + GLES2GPUStateCache * _gpuStateCache{nullptr}; + GLES2GPUBlitManager * _gpuBlitManager{nullptr}; + GLES2GPUConstantRegistry * _gpuConstantRegistry{nullptr}; + GLES2GPUFramebufferCacheMap *_gpuFramebufferCacheMap{nullptr}; + + vector _swapchains; StringArray _extensions; }; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.h b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.h index 2f2bea7f47..d28dfaf7da 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXFramebuffer.h" namespace cc { @@ -35,7 +36,7 @@ class GLES2GPUFramebuffer; class CC_GLES2_API GLES2Framebuffer final : public Framebuffer { public: GLES2Framebuffer(); - ~GLES2Framebuffer(); + ~GLES2Framebuffer() override; inline GLES2GPUFramebuffer *gpuFBO() const { return _gpuFBO; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp new file mode 100644 index 0000000000..a446a0a4fd --- /dev/null +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp @@ -0,0 +1,400 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GLES2GPUObjects.h" + +#define FORCE_DISABLE_VALIDATION 1 + +namespace cc { +namespace gfx { + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION +constexpr uint DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled + +void GL_APIENTRY GLES2EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { + String sourceDesc; + switch (source) { + case GL_DEBUG_SOURCE_API_KHR: sourceDesc = "API"; break; + case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: sourceDesc = "SHADER_COMPILER"; break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR: sourceDesc = "WINDOW_SYSTEM"; break; + case GL_DEBUG_SOURCE_THIRD_PARTY_KHR: sourceDesc = "THIRD_PARTY"; break; + case GL_DEBUG_SOURCE_APPLICATION_KHR: sourceDesc = "APPLICATION"; break; + default: sourceDesc = "OTHER"; + } + + String typeDesc; + switch (type) { + case GL_DEBUG_TYPE_ERROR_KHR: typeDesc = "ERROR"; break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: typeDesc = "PEPRECATED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: typeDesc = "UNDEFINED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_PERFORMANCE_KHR: typeDesc = "PERFORMANCE"; break; + case GL_DEBUG_TYPE_PORTABILITY_KHR: typeDesc = "PORTABILITY"; break; + case GL_DEBUG_TYPE_MARKER_KHR: typeDesc = "MARKER"; break; + case GL_DEBUG_TYPE_PUSH_GROUP_KHR: typeDesc = "PUSH_GROUP"; break; + case GL_DEBUG_TYPE_POP_GROUP_KHR: typeDesc = "POP_GROUP"; break; + default: typeDesc = "OTHER"; + } + + String severityDesc; + switch (severity) { + case GL_DEBUG_SEVERITY_HIGH_KHR: severityDesc = "HIGH"; break; + case GL_DEBUG_SEVERITY_MEDIUM_KHR: severityDesc = "MEDIUM"; break; + case GL_DEBUG_SEVERITY_LOW_KHR: severityDesc = "LOW"; break; + default: severityDesc = "NOTIFICATION"; + } + + String msg = StringUtil::format("source: %s, type: %s, severity: %s, message: %s", + sourceDesc.c_str(), typeDesc.c_str(), severityDesc.c_str(), message); + + if (severity == GL_DEBUG_SEVERITY_HIGH_KHR) { + CC_LOG_ERROR(msg.c_str()); + CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); + } else if (severity == GL_DEBUG_SEVERITY_MEDIUM_KHR) { + CC_LOG_WARNING(msg.c_str()); + } else { + CC_LOG_DEBUG(msg.c_str()); + } +} +#endif + +bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstantRegistry *constantRegistry) { + _stateCache = stateCache; + _constantRegistry = constantRegistry; + + if (!gles2wInit()) { + return false; + } + + EGL_CHECK(eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); + + if (eglDisplay == EGL_NO_DISPLAY) { + CC_LOG_ERROR("eglGetDisplay() - FAILED."); + return false; + } + + EGLBoolean success{false}; + EGL_CHECK(success = eglInitialize(eglDisplay, &eglMajorVersion, &eglMinorVersion)); + + if (!success) { + CC_LOG_ERROR("eglInitialize() - FAILED."); + return false; + } + + EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API)); + + bool msaaEnabled{false}; + bool qualityPreferred{false}; + + EGLint redSize{8}; + EGLint greenSize{8}; + EGLint blueSize{8}; + EGLint alphaSize{8}; + EGLint depthSize{24}; + EGLint stencilSize{8}; + EGLint sampleBufferSize{msaaEnabled ? EGL_DONT_CARE : 0}; + EGLint sampleSize{msaaEnabled ? EGL_DONT_CARE : 0}; + + EGLint defaultAttribs[]{ + EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_BLUE_SIZE, blueSize, + EGL_GREEN_SIZE, greenSize, + EGL_RED_SIZE, redSize, + EGL_ALPHA_SIZE, alphaSize, + EGL_DEPTH_SIZE, depthSize, + EGL_STENCIL_SIZE, stencilSize, + EGL_SAMPLE_BUFFERS, sampleBufferSize, + EGL_SAMPLES, sampleSize, + EGL_NONE}; + + int numConfig{0}; + vector eglConfigs; + + EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, nullptr, 0, &numConfig)); + if (success) { + eglConfigs.resize(numConfig); + } else { + CC_LOG_ERROR("Query configuration failed."); + return false; + } + + int count = numConfig; + EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, eglConfigs.data(), count, &numConfig)); + if (!success || !numConfig) { + CC_LOG_ERROR("eglChooseConfig configuration failed."); + return false; + } + + EGLint depth{0}; + EGLint stencil{0}; + EGLint sampleBuffers{0}; + EGLint sampleCount{0}; + EGLint params[8]{0}; + uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); + + for (int i = 0; i < numConfig; i++) { + int depthValue{0}; + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_RED_SIZE, ¶ms[0]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_GREEN_SIZE, ¶ms[1]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_BLUE_SIZE, ¶ms[2]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_ALPHA_SIZE, ¶ms[3]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_DEPTH_SIZE, ¶ms[4]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_STENCIL_SIZE, ¶ms[5]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_SAMPLE_BUFFERS, ¶ms[6]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_SAMPLES, ¶ms[7]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_DEPTH_ENCODING_NV, &depthValue); + + int bNonLinearDepth = (depthValue == EGL_DEPTH_ENCODING_NONLINEAR_NV) ? 1 : 0; + + /*------------------------------------------ANGLE's priority-----------------------------------------------*/ + // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha + uint64_t currScore{0}; + EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); + currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; + currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; + currScore |= static_cast(std::min(colorScore, 127)) << 17; + currScore |= static_cast(std::min(std::abs(params[4] - depthSize), 63)) << 11; + currScore |= static_cast(std::min(std::abs(1 - bNonLinearDepth), 1)) << 10; + currScore |= static_cast(std::min(std::abs(params[5] - stencilSize), 31)) << 6; + currScore |= static_cast(std::min(std::abs(params[3] - alphaSize), 31)) << 0; + /*------------------------------------------ANGLE's priority-----------------------------------------------*/ + + // if msaaEnabled, sampleBuffers and sampleCount should be greater than 0, until iterate to the last one(can't find). + bool msaaLimit = (msaaEnabled ? (params[6] > 0 && params[7] > 0) : (params[6] == 0 && params[7] == 0)); + // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" + bool filter = (currScore < lastScore) ^ qualityPreferred; + if ((filter && msaaLimit) || (!eglConfig && i == numConfig - 1)) { + eglConfig = eglConfigs[i]; + depth = params[4]; + stencil = params[5]; + sampleBuffers = params[6]; + sampleCount = params[7]; + lastScore = currScore; + } + } + + CC_LOG_INFO("Setup EGLConfig: depth [%d] stencil [%d] sampleBuffer [%d] sampleCount [%d]", depth, stencil, sampleBuffers, sampleCount); + + EGL_CHECK(_extensions = StringUtil::split(eglQueryString(eglDisplay, EGL_EXTENSIONS), " ")); + + bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); + if (hasKHRCreateCtx) { + eglAttributes.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR); + eglAttributes.push_back(2); + eglAttributes.push_back(EGL_CONTEXT_MINOR_VERSION_KHR); + eglAttributes.push_back(0); +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION + eglAttributes.push_back(EGL_CONTEXT_FLAGS_KHR); + eglAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR); +#endif + eglAttributes.push_back(EGL_NONE); + + EGL_CHECK(eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data())); + } else { + eglAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION); + eglAttributes.push_back(2); + eglAttributes.push_back(EGL_NONE); + + EGL_CHECK(eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data())); + } + + if (!eglDefaultContext) { + CC_LOG_ERROR("Create EGL context failed."); + return false; + } + + EGLint pbufferAttribs[]{ + EGL_WIDTH, 1, + EGL_HEIGHT, 1, + EGL_NONE}; + EGL_CHECK(eglDefaultSurface = eglCreatePbufferSurface(eglDisplay, eglConfig, pbufferAttribs)); + + size_t threadID{std::hash{}(std::this_thread::get_id())}; + _sharedContexts[threadID] = eglDefaultContext; + + makeCurrent(eglDefaultSurface, eglDefaultSurface, eglDefaultContext); + resetStates(); + + return true; +} + +void GLES2GPUContext::destroy() { + if (eglDisplay) { + makeCurrent(EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + } + + if (eglDefaultSurface) { + EGL_CHECK(eglDestroySurface(eglDisplay, eglDefaultSurface)); + eglDefaultSurface = EGL_NO_SURFACE; + } + + for (auto pair : _sharedContexts) { + if (pair.second != eglDefaultContext) { + EGL_CHECK(eglDestroyContext(eglDisplay, pair.second)); + } + } + _sharedContexts.clear(); + + if (eglDefaultContext) { + EGL_CHECK(eglDestroyContext(eglDisplay, eglDefaultContext)); + eglDefaultContext = EGL_NO_SURFACE; + } + + if (eglDisplay) { + EGL_CHECK(eglTerminate(eglDisplay)); + eglDisplay = EGL_NO_DISPLAY; + } +} + +void GLES2GPUContext::bindContext(bool bound) { + if (bound) { + makeCurrent(_eglCurrentDrawSurface, _eglCurrentReadSurface, eglDefaultContext); + resetStates(); + } else { + makeCurrent(EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT, false); + } +} + +void GLES2GPUContext::makeCurrent(const GLES2GPUSwapchain *drawSwapchain, const GLES2GPUSwapchain *readSwapchain) { + EGLSurface drawSurface = drawSwapchain ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; + EGLSurface readSurface = readSwapchain ? readSwapchain->eglSurface : _eglCurrentReadSurface; + if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface) return; + + makeCurrent(drawSurface, readSurface, _eglCurrentContext); +} + +void GLES2GPUContext::present(const GLES2GPUSwapchain *swapchain) { + if (_eglCurrentInterval != swapchain->eglSwapInterval) { + if (!eglSwapInterval(eglDisplay, swapchain->eglSwapInterval)) { + CC_LOG_ERROR("eglSwapInterval() - FAILED."); + } + _eglCurrentInterval = swapchain->eglSwapInterval; + } + EGL_CHECK(eglSwapBuffers(eglDisplay, swapchain->eglSurface)); +} + +EGLContext GLES2GPUContext::getSharedContext() { + size_t threadID{std::hash{}(std::this_thread::get_id())}; + if (_sharedContexts.count(threadID)) return _sharedContexts[threadID]; + + EGLContext context = EGL_NO_CONTEXT; + EGL_CHECK(context = eglCreateContext(eglDisplay, eglConfig, eglDefaultContext, eglAttributes.data())); + + if (!context) { + CC_LOG_ERROR("Create shared context failed."); + return EGL_NO_CONTEXT; + } + + _sharedContexts[threadID] = context; + return context; +} + +bool GLES2GPUContext::makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache) { + bool succeeded; + EGL_CHECK(succeeded = eglMakeCurrent(eglDisplay, drawSurface, readSurface, context)); + if (succeeded && updateCache) { + _eglCurrentDrawSurface = drawSurface; + _eglCurrentReadSurface = readSurface; + _eglCurrentContext = context; + } + return succeeded; +} + +void GLES2GPUContext::resetStates() const { + GL_CHECK(glPixelStorei(GL_PACK_ALIGNMENT, 1)); + GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); + GL_CHECK(glActiveTexture(GL_TEXTURE0)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glEnable(GL_SCISSOR_TEST)); + GL_CHECK(glEnable(GL_CULL_FACE)); + GL_CHECK(glCullFace(GL_BACK)); + + GL_CHECK(glFrontFace(GL_CCW)); + + GL_CHECK(glDisable(GL_SAMPLE_COVERAGE)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glEnable(GL_DEPTH_TEST)); + GL_CHECK(glDepthMask(GL_TRUE)); + GL_CHECK(glDepthFunc(GL_LESS)); + + GL_CHECK(glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xffffffff)); + GL_CHECK(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP)); + GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); + GL_CHECK(glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 1, 0xffffffff)); + GL_CHECK(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP)); + GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); + + GL_CHECK(glDisable(GL_STENCIL_TEST)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE)); + GL_CHECK(glDisable(GL_BLEND)); + GL_CHECK(glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD)); + GL_CHECK(glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO)); + GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); + GL_CHECK(glBlendColor(0.0F, 0.0F, 0.0F, 0.0F)); + + GL_CHECK(glUseProgram(0)); + + if (_constantRegistry->useVAO) { + GL_CHECK(glBindVertexArrayOES(0)); + } + + GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); + + GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); + + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION + GL_CHECK(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR)); + if (glDebugMessageControlKHR) { + GL_CHECK(glDebugMessageControlKHR(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE)); + } + if (glDebugMessageCallbackKHR) { + GL_CHECK(glDebugMessageCallbackKHR(GLES2EGLDebugProc, NULL)); + } +#endif + + if (_constantRegistry->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { + GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); + } + + _stateCache->reset(); + + _constantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); + + CC_LOG_DEBUG("EGL context bounded to thread %llx", _constantRegistry->currentBoundThreadID); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index a123d01429..27796e0a7a 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -25,8 +25,6 @@ #pragma once -#include - #include "gfx-base/GFXDef.h" #include "gfx-gles-common/GLESCommandPool.h" @@ -38,8 +36,7 @@ namespace gfx { class GLES2GPUConstantRegistry { public: - uint currentBoundThreadID{0U}; - uint defaultFramebuffer{0U}; + size_t currentBoundThreadID{0U}; MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; FBFSupportLevel mFBF{FBFSupportLevel::NONE}; @@ -50,6 +47,58 @@ public: bool useDiscardFramebuffer = false; }; +class GLES2GPUStateCache; +class GLES2GPUSwapchain; +class GLES2GPUContext final : public Object { +public: + bool initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstantRegistry *constantRegistry); + void destroy(); + + EGLint eglMajorVersion{0}; + EGLint eglMinorVersion{0}; + EGLDisplay eglDisplay{EGL_NO_DISPLAY}; + EGLConfig eglConfig{nullptr}; + vector eglAttributes; + + EGLSurface eglDefaultSurface{EGL_NO_SURFACE}; + EGLContext eglDefaultContext{EGL_NO_CONTEXT}; + + // pass nullptr to keep the current surface + void makeCurrent(const GLES2GPUSwapchain *drawSwapchain = nullptr, const GLES2GPUSwapchain *readSwapchain = nullptr); + void bindContext(bool bound); // for context switching between threads + + void present(const GLES2GPUSwapchain *swapchain); + + inline bool checkExtension(const String &extension) const { + return std::find(_extensions.begin(), _extensions.end(), extension) != _extensions.end(); + } + +private: + bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); + EGLContext getSharedContext(); + void resetStates() const; + + // state caches + EGLSurface _eglCurrentDrawSurface{EGL_NO_SURFACE}; + EGLSurface _eglCurrentReadSurface{EGL_NO_SURFACE}; + EGLContext _eglCurrentContext{EGL_NO_CONTEXT}; + EGLint _eglCurrentInterval{0}; + + GLES2GPUStateCache * _stateCache{nullptr}; + GLES2GPUConstantRegistry *_constantRegistry{nullptr}; + + map _sharedContexts; + + StringArray _extensions; +}; + +class GLES2GPUSwapchain final : public Object { +public: + EGLSurface eglSurface{EGL_NO_SURFACE}; + EGLint eglSwapInterval{0}; + GLuint glFramebuffer{0}; +}; + class GLES2GPUBuffer final : public Object { public: BufferUsage usage = BufferUsage::NONE; @@ -73,31 +122,32 @@ 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; - 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; + 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::ONE}; + 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}; + GLES2GPUSwapchain *swapchain{nullptr}; }; using GLES2GPUTextureList = vector; @@ -229,17 +279,31 @@ public: bool usesFBF = false; struct GLFramebuffer { - GLuint glFramebuffer = 0U; + inline void initialize(GLES2GPUSwapchain *sc) { swapchain = sc; } + inline void initialize(GLuint framebuffer) { _glFramebuffer = framebuffer; } + inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } + + void destroy(GLES2GPUStateCache *cache); + + GLES2GPUSwapchain *swapchain{nullptr}; + + private: + GLuint _glFramebuffer{0U}; + }; + + struct Framebuffer { + GLFramebuffer framebuffer; // for blit-based manual resolving - GLbitfield resolveMask = 0U; - GLuint glResolveFramebuffer = 0U; + GLbitfield resolveMask{0U}; + GLFramebuffer resolveFramebuffer; }; - // one per subpass, if not using FBF - vector instances; - vector uberColorAttachmentIndices; - GLFramebuffer uberInstance; + // one per subpass, if not using FBF + vector instances; + + vector uberColorAttachmentIndices; + Framebuffer uberInstance; }; class GLES2GPUDescriptorSetLayout final : public Object { @@ -461,49 +525,5 @@ private: CacheMap _textureMap; // texture -> framebuffer }; -constexpr size_t CHUNK_SIZE = 16 * 1024 * 1024; // 16M per block by default -class GLES2GPUStagingBufferPool final : public Object { -public: - ~GLES2GPUStagingBufferPool() override { - for (Buffer &buffer : _pool) { - CC_FREE(buffer.mappedData); - } - _pool.clear(); - } - - uint8_t *alloc(size_t size) { - size_t bufferCount = _pool.size(); - Buffer *buffer = nullptr; - for (size_t idx = 0U; idx < bufferCount; idx++) { - Buffer *cur = &_pool[idx]; - if (CHUNK_SIZE - cur->curOffset >= size) { - buffer = cur; - break; - } - } - if (!buffer) { - _pool.resize(bufferCount + 1); - buffer = &_pool.back(); - buffer->mappedData = static_cast(CC_MALLOC(CHUNK_SIZE)); - } - uint8_t *data = buffer->mappedData + buffer->curOffset; - buffer->curOffset += size; - return data; - } - - void reset() { - for (Buffer &buffer : _pool) { - buffer.curOffset = 0U; - } - } - -private: - struct Buffer { - uint8_t *mappedData = nullptr; - size_t curOffset = 0U; - }; - vector _pool; -}; - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp index 12830b1f57..05bdf06f28 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp @@ -68,15 +68,5 @@ void GLES2InputAssembler::doDestroy() { } } -void GLES2InputAssembler::ExtractCmdDraw(GLES2CmdDraw *cmd) { - cmd->drawInfo.vertexCount = _vertexCount; - cmd->drawInfo.firstVertex = _firstVertex; - cmd->drawInfo.indexCount = _indexCount; - cmd->drawInfo.firstIndex = _firstIndex; - cmd->drawInfo.vertexOffset = _vertexOffset; - cmd->drawInfo.instanceCount = _instanceCount; - cmd->drawInfo.firstInstance = _firstInstance; -} - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.h b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.h index cb9acaa769..f76feca56a 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.h +++ b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXInputAssembler.h" namespace cc { @@ -36,9 +37,7 @@ class GLES2CmdDraw; class CC_GLES2_API GLES2InputAssembler final : public InputAssembler { public: GLES2InputAssembler(); - ~GLES2InputAssembler(); - - void ExtractCmdDraw(GLES2CmdDraw *cmd); + ~GLES2InputAssembler() override; inline GLES2GPUInputAssembler *gpuInputAssembler() const { return _gpuInputAssembler; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.h b/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.h index 123ce4dd8e..355261113a 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES2_PIPELINE_LAYOUT_H_ -#define CC_GFXGLES2_PIPELINE_LAYOUT_H_ +#pragma once +#include "GLES2Std.h" #include "gfx-base/GFXPipelineLayout.h" namespace cc { @@ -36,7 +36,7 @@ class GLES2GPUPipelineLayout; class CC_GLES2_API GLES2PipelineLayout final : public PipelineLayout { public: GLES2PipelineLayout(); - ~GLES2PipelineLayout(); + ~GLES2PipelineLayout() override; inline GLES2GPUPipelineLayout *gpuPipelineLayout() const { return _gpuPipelineLayout; } @@ -49,5 +49,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES2_PIPELINE_LAYOUT_H_ diff --git a/native/cocos/renderer/gfx-gles2/GLES2PipelineState.h b/native/cocos/renderer/gfx-gles2/GLES2PipelineState.h index e9d889dbe9..384b3d5ea4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PipelineState.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PipelineState.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXPipelineState.h" namespace cc { @@ -35,7 +36,7 @@ class GLES2GPUPipelineState; class CC_GLES2_API GLES2PipelineState final : public PipelineState { public: GLES2PipelineState(); - ~GLES2PipelineState(); + ~GLES2PipelineState() override; inline GLES2GPUPipelineState *gpuPipelineState() const { return _gpuPipelineState; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp index b09cac3946..65dd2bde32 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp @@ -26,6 +26,7 @@ #include "GLES2Std.h" #include "GLES2Buffer.h" +#include "GLES2Commands.h" #include "GLES2DescriptorSet.h" #include "GLES2Device.h" #include "GLES2Framebuffer.h" diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h index d4c8a253ce..fa72a8f3fa 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h @@ -26,7 +26,6 @@ #pragma once #include "GLES2CommandBuffer.h" -#include "GLES2Std.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles2/GLES2Queue.h b/native/cocos/renderer/gfx-gles2/GLES2Queue.h index d124c01cd5..a6bccd1bdd 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Queue.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Queue.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXQueue.h" namespace cc { @@ -33,7 +34,7 @@ namespace gfx { class CC_GLES2_API GLES2Queue final : public Queue { public: GLES2Queue(); - ~GLES2Queue(); + ~GLES2Queue() override; void submit(CommandBuffer *const *cmdBuffs, uint count) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp index d6a1efe173..0fbee51df8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp @@ -52,15 +52,8 @@ void GLES2RenderPass::doInit(const RenderPassInfo & /*info*/) { for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; } - subpass.depthStencil = _colorAttachments.size(); - } else { - // the depth stencil attachment is the default fallback - // when none are specified in subpass - const bool hasDepth = _depthStencilAttachment.format != Format::UNKNOWN; - for (auto &subpass : _gpuRenderPass->subpasses) { - if (hasDepth && subpass.depthStencil == INVALID_BINDING) { - subpass.depthStencil = static_cast(_colorAttachments.size()); - } + if (_depthStencilAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = _colorAttachments.size(); } } } diff --git a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.h b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.h index 16f966ad8c..0eb3b22fec 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.h +++ b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXRenderPass.h" namespace cc { @@ -35,7 +36,7 @@ class GLES2GPURenderPass; class CC_GLES2_API GLES2RenderPass final : public RenderPass { public: GLES2RenderPass(); - ~GLES2RenderPass(); + ~GLES2RenderPass() override; inline GLES2GPURenderPass *gpuRenderPass() const { return _gpuRenderPass; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2Shader.h b/native/cocos/renderer/gfx-gles2/GLES2Shader.h index eb641e5aa8..0e35336075 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Shader.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Shader.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXShader.h" namespace cc { @@ -35,7 +36,7 @@ class GLES2GPUShader; class CC_GLES2_API GLES2Shader final : public Shader { public: GLES2Shader(); - ~GLES2Shader(); + ~GLES2Shader() override; inline GLES2GPUShader *gpuShader() const { return _gpuShader; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp new file mode 100644 index 0000000000..10b2ba9113 --- /dev/null +++ b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp @@ -0,0 +1,155 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GLES2Swapchain.h" +#include "GLES2Device.h" +#include "GLES2GPUObjects.h" +#include "GLES2Texture.h" + +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include "android/native_window.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include + #include +#endif + +namespace cc { +namespace gfx { + +GLES2Swapchain::GLES2Swapchain() { + _typedID = generateObjectID(); +} + +GLES2Swapchain::~GLES2Swapchain() { + destroy(); +} + +void GLES2Swapchain::doInit(const SwapchainInfo& info) { + const auto* context = GLES2Device::getInstance()->context(); + _gpuSwapchain = CC_NEW(GLES2GPUSwapchain); + auto* window = reinterpret_cast(info.windowHandle); + +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS + EGLint nFmt; + if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { + CC_LOG_ERROR("Getting configuration attributes failed."); + return; + } + + auto width = static_cast(info.width); + auto height = static_cast(info.height); + + #if CC_PLATFORM == CC_PLATFORM_ANDROID + ANativeWindow_setBuffersGeometry(window, width, height, nFmt); + #elif CC_PLATFORM == CC_PLATFORM_OHOS + NativeLayerHandle(window, NativeLayerOps::SET_WIDTH_AND_HEIGHT, width, height); + NativeLayerHandle(window, NativeLayerOps::SET_FORMAT, nFmt); + #endif +#endif + + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Create window surface failed."); + return; + } + + switch (_vsyncMode) { + case VsyncMode::OFF: _gpuSwapchain->eglSwapInterval = 0; break; + case VsyncMode::ON: + case VsyncMode::RELAXED: _gpuSwapchain->eglSwapInterval = 1; break; + case VsyncMode::MAILBOX: _gpuSwapchain->eglSwapInterval = 0; break; + case VsyncMode::HALF: _gpuSwapchain->eglSwapInterval = 2; break; + default: break; + } + + ///////////////////// Texture Creation ///////////////////// + + _colorTexture = CC_NEW(GLES2Texture); + _depthStencilTexture = CC_NEW(GLES2Texture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = Format::DEPTH_STENCIL; + initTexture(textureInfo, _depthStencilTexture); +} + +void GLES2Swapchain::doDestroy() { + if (!_gpuSwapchain) return; + + CC_SAFE_DESTROY(_depthStencilTexture) + CC_SAFE_DESTROY(_colorTexture) + + doDestroySurface(); + CC_SAFE_DELETE(_gpuSwapchain); +} + +void GLES2Swapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform /*transform*/) { + _colorTexture->resize(width, height); + _depthStencilTexture->resize(width, height); +} + +void GLES2Swapchain::doDestroySurface() { + if (_gpuSwapchain->eglSurface != EGL_NO_SURFACE) { + const auto* context = GLES2Device::getInstance()->context(); + eglDestroySurface(context->eglDisplay, _gpuSwapchain->eglSurface); + EGL_CHECK(eglMakeCurrent(context->eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); + _gpuSwapchain->eglSurface = EGL_NO_SURFACE; + } +} + +void GLES2Swapchain::doCreateSurface(void* windowHandle) { + auto* context = GLES2Device::getInstance()->context(); + auto* window = reinterpret_cast(windowHandle); + + EGLint nFmt = 0; + if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { + CC_LOG_ERROR("Getting configuration attributes failed."); + return; + } + +// Device's size will be updated after recreate window (in resize event) and is incorrect for now. +#if CC_PLATFORM == CC_PLATFORM_ANDROID + int32_t width = ANativeWindow_getWidth(window); + int32_t height = ANativeWindow_getHeight(window); + ANativeWindow_setBuffersGeometry(window, width, height, nFmt); +#elif CC_PLATFORM == CC_PLATFORM_OHOS + int32_t width = NativeLayerHandle(window, NativeLayerOps::GET_WIDTH); + int32_t height = NativeLayerHandle(window, NativeLayerOps::GET_HEIGHT); +#endif + + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Recreate window surface failed."); + return; + } +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.h b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.h new file mode 100644 index 0000000000..704a7cc0b7 --- /dev/null +++ b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.h @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "GLES2Std.h" +#include "gfx-base/GFXSwapchain.h" + +namespace cc { +namespace gfx { + +class GLES2GPUSwapchain; + +class CC_GLES2_API GLES2Swapchain final : public Swapchain { +public: + GLES2Swapchain(); + ~GLES2Swapchain() override; + + inline GLES2GPUSwapchain *gpuSwapchain() const { return _gpuSwapchain; } + +protected: + void doInit(const SwapchainInfo &info) override; + void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; + + GLES2GPUSwapchain *_gpuSwapchain{nullptr}; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp index 2f7b8e12dc..1dc2519431 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp @@ -27,6 +27,7 @@ #include "GLES2Commands.h" #include "GLES2Device.h" +#include "GLES2Swapchain.h" #include "GLES2Texture.h" namespace cc { @@ -42,22 +43,25 @@ GLES2Texture::~GLES2Texture() { void GLES2Texture::doInit(const TextureInfo& /*info*/) { _gpuTexture = CC_NEW(GLES2GPUTexture); - _gpuTexture->type = _type; - _gpuTexture->format = _format; - _gpuTexture->usage = _usage; - _gpuTexture->width = _width; - _gpuTexture->height = _height; - _gpuTexture->depth = _depth; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayer = _info.layerCount; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->arrayLayer = _layerCount; - _gpuTexture->mipLevel = _levelCount; - _gpuTexture->samples = _samples; - _gpuTexture->flags = _flags; - _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_width) && math::IsPowerOfTwo(_height); + _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); + _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES2CreateTexture(GLES2Device::getInstance(), _gpuTexture); - GLES2Device::getInstance()->getMemoryStatus().textureSize += _size; + if (!_gpuTexture->memoryless) { + GLES2Device::getInstance()->getMemoryStatus().textureSize += _size; + } } void GLES2Texture::doInit(const TextureViewInfo& /*info*/) { @@ -65,9 +69,10 @@ void GLES2Texture::doInit(const TextureViewInfo& /*info*/) { } void GLES2Texture::doDestroy() { - GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; - if (_gpuTexture) { + if (!_gpuTexture->memoryless) { + GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; + } cmdFuncGLES2DestroyTexture(GLES2Device::getInstance(), _gpuTexture); CC_DELETE(_gpuTexture); _gpuTexture = nullptr; @@ -75,14 +80,36 @@ void GLES2Texture::doDestroy() { } void GLES2Texture::doResize(uint width, uint height, uint size) { - GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; - + if (!_gpuTexture->memoryless) { + GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; + } _gpuTexture->width = width; _gpuTexture->height = height; _gpuTexture->size = size; cmdFuncGLES2ResizeTexture(GLES2Device::getInstance(), _gpuTexture); - GLES2Device::getInstance()->getMemoryStatus().textureSize += size; + if (!_gpuTexture->memoryless) { + GLES2Device::getInstance()->getMemoryStatus().textureSize += size; + } +} + +///////////////////////////// Swapchain Specific ///////////////////////////// + +void GLES2Texture::doInit(const SwapchainTextureInfo& /*info*/) { + _gpuTexture = CC_NEW(GLES2GPUTexture); + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayer = _info.layerCount; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; + _gpuTexture->memoryless = true; + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.h b/native/cocos/renderer/gfx-gles2/GLES2Texture.h index 19ccab459e..9d97a5870d 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES2Std.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -35,7 +36,7 @@ class GLES2GPUTexture; class CC_GLES2_API GLES2Texture final : public Texture { public: GLES2Texture(); - ~GLES2Texture(); + ~GLES2Texture() override; inline GLES2GPUTexture *gpuTexture() const { return _gpuTexture; } @@ -44,6 +45,7 @@ protected: void doInit(const TextureViewInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; + void doInit(const SwapchainTextureInfo &info) override; GLES2GPUTexture *_gpuTexture = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Wrangler.mm b/native/cocos/renderer/gfx-gles2/GLES2Wrangler.mm deleted file mode 100644 index a04d76663d..0000000000 --- a/native/cocos/renderer/gfx-gles2/GLES2Wrangler.mm +++ /dev/null @@ -1,110 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES2Wrangler.h" - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - #import - #import - #import - #import - #import - #import - -static CFBundleRef g_es2Bundle; -static CFURLRef g_es2BundleURL; - -static int gles2wOpen() { - #if TARGET_IPHONE_SIMULATOR - CFStringRef frameworkPath = CFSTR("/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks/OpenGLES.framework"); - #else - CFStringRef frameworkPath = CFSTR("/System/Library/Frameworks/OpenGLES.framework"); - #endif - - g_es2BundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, - frameworkPath, - kCFURLPOSIXPathStyle, true); - - CFRelease(frameworkPath); - - g_es2Bundle = CFBundleCreate(kCFAllocatorDefault, g_es2BundleURL); - - return (g_es2Bundle != NULL); -} - -static void *gles2wLoad(const char *proc) { - void *res; - - CFStringRef procname = CFStringCreateWithCString(kCFAllocatorDefault, proc, - kCFStringEncodingASCII); - res = CFBundleGetFunctionPointerForName(g_es2Bundle, procname); - CFRelease(procname); - return res; -} -#else - // macos - #include - #include - #include - #import - #import - -static void *libegl; -static void *libgl; - -static int gles2wOpen() { - NSURL *appURL = [[NSBundle mainBundle] bundleURL]; - - std::string libPath(appURL.resourceSpecifier.UTF8String); - libPath.append("/Contents/Frameworks/libEGL.dylib"); - libegl = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_LAZY); - if (!libegl) printf("%s\n", dlerror()); - - libPath = appURL.resourceSpecifier.UTF8String; - libPath.append("/Contents/Frameworks/libGLESv2.dylib"); - libgl = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_LAZY); - if (!libgl) printf("%s\n", dlerror()); - - return (libegl && libgl); -} - -static void *gles2wLoad(const char *proc) { - void *res = nullptr; - if (eglGetProcAddress) res = (void *)eglGetProcAddress(proc); - if (!res) res = (void *)dlsym(libegl, proc); - return res; -} -#endif - -bool gles2wInit() { - if (!gles2wOpen()) { - return false; - } - - eglwLoadProcs(gles2wLoad); - gles2wLoadProcs(gles2wLoad); - - return true; -} diff --git a/native/cocos/renderer/gfx-gles2/GLES2Sampler.cpp b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp similarity index 80% rename from native/cocos/renderer/gfx-gles2/GLES2Sampler.cpp rename to native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp index f2c264b316..82ff2cfd35 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Sampler.cpp +++ b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp @@ -23,36 +23,28 @@ THE SOFTWARE. ****************************************************************************/ -#include "GLES2Std.h" - -#include "GLES2Commands.h" -#include "GLES2Device.h" #include "GLES2Sampler.h" +#include "../GLES2Commands.h" +#include "../GLES2Device.h" namespace cc { namespace gfx { -GLES2Sampler::GLES2Sampler() { +GLES2Sampler::GLES2Sampler(const SamplerInfo &info) : Sampler(info) { _typedID = generateObjectID(); -} -GLES2Sampler::~GLES2Sampler() { - destroy(); -} - -void GLES2Sampler::doInit(const SamplerInfo& /*info*/) { _gpuSampler = CC_NEW(GLES2GPUSampler); - _gpuSampler->minFilter = _minFilter; - _gpuSampler->magFilter = _magFilter; - _gpuSampler->mipFilter = _mipFilter; - _gpuSampler->addressU = _addressU; - _gpuSampler->addressV = _addressV; - _gpuSampler->addressW = _addressW; + _gpuSampler->minFilter = _info.minFilter; + _gpuSampler->magFilter = _info.magFilter; + _gpuSampler->mipFilter = _info.mipFilter; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; cmdFuncGLES2CreateSampler(GLES2Device::getInstance(), _gpuSampler); } -void GLES2Sampler::doDestroy() { +GLES2Sampler::~GLES2Sampler() { if (_gpuSampler) { cmdFuncGLES2DestroySampler(GLES2Device::getInstance(), _gpuSampler); CC_DELETE(_gpuSampler); diff --git a/native/cocos/renderer/gfx-base/GFXContext.cpp b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.h similarity index 77% rename from native/cocos/renderer/gfx-base/GFXContext.cpp rename to native/cocos/renderer/gfx-gles2/states/GLES2Sampler.h index 5d25122134..efe99dea96 100644 --- a/native/cocos/renderer/gfx-base/GFXContext.cpp +++ b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.h @@ -23,27 +23,27 @@ THE SOFTWARE. ****************************************************************************/ -#include "base/CoreStd.h" +#pragma once -#include "GFXContext.h" +#include "../GLES2Std.h" +#include "gfx-base/GFXDef-common.h" +#include "gfx-base/states/GFXSampler.h" namespace cc { namespace gfx { -Context::Context() = default; +class GLES2GPUSampler; -Context::~Context() = default; +class CC_GLES2_API GLES2Sampler final : public Sampler { +public: + explicit GLES2Sampler(const SamplerInfo &info); + ~GLES2Sampler() override; -bool Context::initialize(const ContextInfo& info) { - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; + inline GLES2GPUSampler *gpuSampler() const { return _gpuSampler; } - return doInit(info); -} - -void Context::destroy() { - doDestroy(); -} +protected: + GLES2GPUSampler *_gpuSampler = nullptr; +}; } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 9cb62b6e54..c655deed88 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -27,14 +27,15 @@ #include "GLES3Buffer.h" #include "GLES3CommandBuffer.h" +#include "GLES3Commands.h" #include "GLES3DescriptorSet.h" #include "GLES3Device.h" #include "GLES3Framebuffer.h" -#include "GLES3GlobalBarrier.h" #include "GLES3InputAssembler.h" #include "GLES3PipelineState.h" #include "GLES3RenderPass.h" #include "GLES3Texture.h" +#include "states/GLES3GlobalBarrier.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index 98758dc07f..4924fa6a78 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -25,14 +25,17 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXCommandBuffer.h" -#include "GLES3Commands.h" - namespace cc { namespace gfx { class GLES3GPUCommandAllocator; +class GLES3CmdPackage; +class GLES3GPUPipelineState; +class GLES3GPUInputAssembler; +class GLES3GPUDescriptorSet; class CC_GLES3_API GLES3CommandBuffer : public CommandBuffer { public: diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index e192a03261..bd0baa09ad 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -27,7 +27,6 @@ #include "GLES3Commands.h" #include "GLES3Device.h" -#include "gfx-gles-common/GLESCommandPool.h" #define BUFFER_OFFSET(idx) (static_cast(0) + (idx)) @@ -92,12 +91,8 @@ GLenum mapGLInternalFormat(Format format) { case Format::RGB10A2: return GL_RGB10_A2; 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_DEPTH24_STENCIL8; - case Format::D24: return GL_DEPTH_COMPONENT24; - case Format::D24S8: return GL_DEPTH24_STENCIL8; - case Format::D32F: return GL_DEPTH_COMPONENT32F; - case Format::D32F_S8: return GL_DEPTH32F_STENCIL8; + case Format::DEPTH: return GL_DEPTH_COMPONENT32F; + case Format::DEPTH_STENCIL: return GL_DEPTH32F_STENCIL8; case Format::BC1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case Format::BC1_ALPHA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; @@ -185,7 +180,7 @@ GLenum mapGLFormat(Format format) { case Format::RGB32F: case Format::R11G11B10F: case Format::R5G6B5: - case Format::RGB9E5: + case Format::RGB9E5: case Format::SRGB8: return GL_RGB; case Format::RGBA8: case Format::RGBA8SN: @@ -222,12 +217,8 @@ GLenum mapGLFormat(Format format) { case Format::RGBA32I: case Format::RGB10A2UI: return GL_RGBA_INTEGER; - case Format::D16: return GL_DEPTH_COMPONENT; - case Format::D16S8: return GL_DEPTH_STENCIL; - case Format::D24: return GL_DEPTH_COMPONENT; - case Format::D24S8: return GL_DEPTH_STENCIL; - case Format::D32F: return GL_DEPTH_COMPONENT; - case Format::D32F_S8: return GL_DEPTH_STENCIL; + case Format::DEPTH: return GL_DEPTH_COMPONENT; + case Format::DEPTH_STENCIL: return GL_DEPTH_STENCIL; case Format::BC1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case Format::BC1_ALPHA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; @@ -422,12 +413,8 @@ GLenum formatToGLType(Format format) { case Format::RGB10A2UI: return GL_UNSIGNED_INT_2_10_10_10_REV; case Format::RGB9E5: return GL_UNSIGNED_INT_5_9_9_9_REV; - case Format::D16: return GL_UNSIGNED_SHORT; - case Format::D16S8: return GL_UNSIGNED_INT_24_8; // no D16S8 support - case Format::D24: return GL_UNSIGNED_INT; - case Format::D24S8: return GL_UNSIGNED_INT_24_8; - case Format::D32F: return GL_FLOAT; - case Format::D32F_S8: return GL_FLOAT_32_UNSIGNED_INT_24_8_REV; + case Format::DEPTH: return GL_FLOAT; + case Format::DEPTH_STENCIL: return GL_FLOAT_32_UNSIGNED_INT_24_8_REV; case Format::BC1: case Format::BC1_SRGB: @@ -629,6 +616,17 @@ const GLenum GL_MEMORY_ACCESS[] = { GL_WRITE_ONLY, GL_READ_WRITE, }; + +const GLint GL_SAMPLE_COUNT[] = { + 1, + 2, +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS + 4, +#else + 8, +#endif + 16, +}; } // namespace void cmdFuncGLES3CreateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { @@ -852,13 +850,13 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); - if (gpuTexture->samples > SampleCount::X1) { + if (gpuTexture->samples > SampleCount::ONE) { 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); + auto requestedSampleCount = GL_SAMPLE_COUNT[toNumber(gpuTexture->samples)]; for (GLint sampleCount : supportedSampleCounts) { if (sampleCount <= requestedSampleCount) { gpuTexture->glSamples = sampleCount; @@ -884,6 +882,11 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) return; } + if (gpuTexture->glTexture) { + gpuTexture->glTarget = GL_TEXTURE_EXTERNAL_OES; + return; + } + if (gpuTexture->glSamples <= 1) { switch (gpuTexture->type) { case TextureType::TEX2D: { @@ -897,9 +900,7 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) } 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 { + if (hasFlag(gpuTexture->flags, TextureFlagBit::RESIZABLE)) { if (!GFX_FORMAT_INFOS[toNumber(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)); @@ -914,6 +915,8 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) h = std::max(1U, h >> 1); } } + } else { + GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); } } break; @@ -929,9 +932,7 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) } 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 { + if (hasFlag(gpuTexture->flags, TextureFlagBit::RESIZABLE)) { if (!GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].isCompressed) { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { for (uint f = 0; f < 6; ++f) { @@ -950,6 +951,8 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) h = std::max(1U, h >> 1); } } + } else { + GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); } } break; @@ -982,14 +985,15 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) 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; } } - GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->glTarget != GL_TEXTURE_EXTERNAL_OES) { + GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); + } gpuTexture->glTexture = 0; } else if (gpuTexture->glRenderbuffer) { @@ -1004,7 +1008,7 @@ void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture } void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { - if (gpuTexture->memoryless) return; + if (gpuTexture->memoryless || gpuTexture->glTarget == GL_TEXTURE_EXTERNAL_OES) return; if (gpuTexture->glSamples <= 1) { switch (gpuTexture->type) { @@ -1147,7 +1151,6 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { for (size_t i = 0; i < gpuShader->gpuStages.size(); ++i) { GLES3GPUShaderStage &gpuStage = gpuShader->gpuStages[i]; - uint version = 300; switch (gpuStage.type) { case ShaderStageFlagBit::VERTEX: { @@ -1163,7 +1166,6 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { case ShaderStageFlagBit::COMPUTE: { glShaderStage = GL_COMPUTE_SHADER; shaderStageStr = "Compute Shader"; - version = 310; break; } default: { @@ -1173,6 +1175,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { } GL_CHECK(gpuStage.glShader = glCreateShader(glShaderStage)); + uint version = device->constantRegistry()->glMinorVersion ? 310 : 300; String shaderSource = StringUtil::format("#version %u es\n", version) + gpuStage.source; const char *source = shaderSource.c_str(); GL_CHECK(glShaderSource(gpuStage.glShader, 1, (const GLchar **)&source, nullptr)); @@ -1320,8 +1323,9 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { glBuffer.set = buffer.set; glBuffer.binding = buffer.binding; - // no way to specify SSBO bindings here until 4.3 core - GLenum prop = GL_BUFFER_BINDING; + static GLenum prop = GL_BUFFER_BINDING; + + // SSBO bindings should already be specified in shader layout qualifiers GL_CHECK(glGetProgramResourceiv(gpuShader->glProgram, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 1, nullptr, (GLint *)&glBuffer.glBinding)); break; } @@ -1532,7 +1536,7 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl } static GLuint doCreateFramebuffer(GLES3Device * device, - const vector &attachments, const uint *colors, uint colorCount, + const vector &attachments, const uint *colors, size_t colorCount, const GLES3GPUTexture *depthStencil, const uint * resolves = nullptr, const GLES3GPUTexture *depthStencilResolve = nullptr, @@ -1579,7 +1583,7 @@ static GLuint doCreateFramebuffer(GLES3Device * device, 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 { + } else if (depthStencil->glRenderbuffer) { GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glRenderbuffer)); } @@ -1587,7 +1591,7 @@ static GLuint doCreateFramebuffer(GLES3Device * device, if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; } - GL_CHECK(glDrawBuffers(drawBuffers.size(), drawBuffers.data())); + GL_CHECK(glDrawBuffers(utils::toUint(drawBuffers.size()), drawBuffers.data())); GLenum status; GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); @@ -1617,38 +1621,54 @@ static GLuint doCreateFramebuffer(GLES3Device * device, return glFramebuffer; } +static GLES3GPUSwapchain *getSwapchainIfExists(const vector &textures, const uint32_t *indices, size_t count) { + GLES3GPUSwapchain *swapchain{nullptr}; + if (indices) { + size_t offscreenCount{0}; + for (size_t i = 0; i < count; ++i) { + auto *colorTexture = textures[indices[i]]; + if (colorTexture->swapchain) { + swapchain = colorTexture->swapchain; + } else { + ++offscreenCount; + } + } + CCASSERT(!offscreenCount || offscreenCount == count, "Partially offscreen FBO is not supported"); + } + return swapchain; +} + static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO, const vector &colors, - uint depthStencil, GLES3GPUFramebuffer::GLFramebuffer *outFBO, + uint depthStencil, GLES3GPUFramebuffer::Framebuffer *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"); + GLES3GPUSwapchain *swapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, colors.data(), colors.size())}; + if (!swapchain) { + 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; + } - 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); + outFBO->framebuffer.initialize(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); + size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + GLES3GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, resolves, resolveCount)}; + if (!resolveSwapchain) { + outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture)); + } else { + outFBO->resolveFramebuffer.initialize(resolveSwapchain); + } } } else { - outFBO->glFramebuffer = device->constantRegistry()->defaultFramebuffer; + outFBO->framebuffer.initialize(swapchain); } } @@ -1668,7 +1688,7 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu if (GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].hasDepth) continue; gpuFBO->uberColorAttachmentIndices.push_back(i); } - doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); + doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, utils::toUint(gpuFBO->gpuColorTextures.size()), &gpuFBO->uberInstance); } else { for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), @@ -1677,34 +1697,111 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu } } -static void doDestroyFramebuffer(GLES3GPUStateCache *cache, GLuint *pFBO) { - if (cache->glDrawFramebuffer == *pFBO) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - cache->glDrawFramebuffer = 0; +void GLES3GPUFramebuffer::GLFramebuffer::destroy(GLES3GPUStateCache *cache) { + if (swapchain) { + swapchain = nullptr; + } else { + if (cache->glDrawFramebuffer == _glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); + cache->glDrawFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, &_glFramebuffer)); + _glFramebuffer = 0U; } - GL_CHECK(glDeleteFramebuffers(1, pFBO)); - *pFBO = 0U; } void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { - auto *cache = device->stateCache(); - uint defaultFBO = device->constantRegistry()->defaultFramebuffer; + auto *cache = device->stateCache(); for (auto &instance : gpuFBO->instances) { - if (instance.glFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &instance.glFramebuffer); - } - if (instance.glResolveFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &instance.glResolveFramebuffer); - } + instance.framebuffer.destroy(cache); + instance.resolveFramebuffer.destroy(cache); } gpuFBO->instances.clear(); - if (gpuFBO->uberInstance.glFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glFramebuffer); + gpuFBO->uberInstance.framebuffer.destroy(cache); + gpuFBO->uberInstance.resolveFramebuffer.destroy(cache); +} + +void cmdFuncGLES3CreateGlobalBarrier(const std::vector &prevAccesses, const std::vector &nextAccesses, GLES3GPUGlobalBarrier *barrier) { + bool hasShaderWrites = false; + for (auto prevAccesse : prevAccesses) { + switch (prevAccesse) { + case AccessType::COMPUTE_SHADER_WRITE: + case AccessType::VERTEX_SHADER_WRITE: + case AccessType::FRAGMENT_SHADER_WRITE: + case AccessType::COLOR_ATTACHMENT_WRITE: + case AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE: + hasShaderWrites = true; + break; + default: + break; + } } - if (gpuFBO->uberInstance.glResolveFramebuffer != defaultFBO) { - doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glResolveFramebuffer); + + if (hasShaderWrites) { + for (auto nextAccesse : nextAccesses) { + switch (nextAccesse) { + case AccessType::INDIRECT_BUFFER: + barrier->glBarriers |= GL_COMMAND_BARRIER_BIT; + break; + case AccessType::INDEX_BUFFER: + barrier->glBarriers |= GL_ELEMENT_ARRAY_BARRIER_BIT; + break; + case AccessType::VERTEX_BUFFER: + barrier->glBarriers |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; + break; + case AccessType::COMPUTE_SHADER_READ_UNIFORM_BUFFER: + case AccessType::VERTEX_SHADER_READ_UNIFORM_BUFFER: + case AccessType::FRAGMENT_SHADER_READ_UNIFORM_BUFFER: + barrier->glBarriersByRegion |= GL_UNIFORM_BARRIER_BIT; + break; + case AccessType::COMPUTE_SHADER_READ_TEXTURE: + case AccessType::VERTEX_SHADER_READ_TEXTURE: + case AccessType::FRAGMENT_SHADER_READ_TEXTURE: + case AccessType::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT: + case AccessType::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT: + barrier->glBarriersByRegion |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; + barrier->glBarriersByRegion |= GL_TEXTURE_FETCH_BARRIER_BIT; + break; + case AccessType::COMPUTE_SHADER_READ_OTHER: + case AccessType::VERTEX_SHADER_READ_OTHER: + case AccessType::FRAGMENT_SHADER_READ_OTHER: + barrier->glBarriersByRegion |= GL_SHADER_STORAGE_BARRIER_BIT; + break; + case AccessType::COLOR_ATTACHMENT_READ: + case AccessType::DEPTH_STENCIL_ATTACHMENT_READ: + barrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; + break; + case AccessType::TRANSFER_READ: + barrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; + barrier->glBarriers |= GL_TEXTURE_UPDATE_BARRIER_BIT; + barrier->glBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT; + barrier->glBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT; + break; + case AccessType::COMPUTE_SHADER_WRITE: + case AccessType::VERTEX_SHADER_WRITE: + case AccessType::FRAGMENT_SHADER_WRITE: + barrier->glBarriersByRegion |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; + barrier->glBarriersByRegion |= GL_SHADER_STORAGE_BARRIER_BIT; + break; + case AccessType::COLOR_ATTACHMENT_WRITE: + case AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE: + barrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; + break; + case AccessType::TRANSFER_WRITE: + barrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; + barrier->glBarriers |= GL_TEXTURE_UPDATE_BARRIER_BIT; + barrier->glBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT; + barrier->glBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT; + break; + case AccessType::HOST_PREINITIALIZED: + case AccessType::HOST_WRITE: + case AccessType::PRESENT: + default: + break; + } + } } } @@ -1735,10 +1832,14 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } if (gpuFramebuffer && gpuRenderPass) { - const auto &instance = gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[subpassIdx]; - if (cache->glDrawFramebuffer != instance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, instance.glFramebuffer)); - cache->glDrawFramebuffer = instance.glFramebuffer; + auto &instance = gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[subpassIdx]; + + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + device->context()->makeCurrent(instance.framebuffer.swapchain, instance.framebuffer.swapchain); + + if (cache->glDrawFramebuffer != glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glFramebuffer)); + cache->glDrawFramebuffer = glFramebuffer; } if (cache->viewport.left != renderArea->x || @@ -1763,8 +1864,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR cache->scissor.height = renderArea->height; } - GLbitfield glClears = 0; - bool hasBoundFBO = instance.glFramebuffer; + GLbitfield glClears = 0; invalidAttachments.clear(); static const Color ZERO; @@ -1783,7 +1883,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } const Color &color = clearToZero ? ZERO : clearColors[attachmentIndex]; - if (hasBoundFBO) { + if (glFramebuffer) { fColors[0] = color.x; fColors[1] = color.y; fColors[2] = color.z; @@ -1796,7 +1896,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); + invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); break; } } @@ -1817,7 +1917,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR glClears |= GL_DEPTH_BUFFER_BIT; break; case LoadOp::DISCARD: - invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); + invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); break; } } @@ -1836,13 +1936,13 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR glClears |= GL_STENCIL_BUFFER_BIT; } break; case LoadOp::DISCARD: - invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); + invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); break; } } if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); } if (glClears) { @@ -1875,6 +1975,8 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR uint glAttachmentIndex = 0U; if (gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF) { if (subpassIdx == 0) { + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers[0].glBarriers, gpuRenderPass->barriers[0].glBarriersByRegion); + if (gpuFramebuffer->usesPLS) { GL_CHECK(glEnable(GL_SHADER_PIXEL_LOCAL_STORAGE_EXT)); cache->isPLSEnabled = true; @@ -1886,6 +1988,8 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR performDepthStencilLoadOp(); } } else { + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers[subpassIdx].glBarriers, gpuRenderPass->barriers[subpassIdx].glBarriersByRegion); + for (const auto attachmentIndex : gpuRenderPass->subpasses[subpassIdx].colors) { if (attachmentLoadOpRecord & (1 << attachmentIndex)) continue; performLoadOp(attachmentIndex, glAttachmentIndex++, false); @@ -1896,19 +2000,32 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } } +static void ensureScissorRect(GLES3GPUStateCache *cache, int32_t x, int32_t y, uint32_t width, uint32_t height) { + if (cache->scissor.x > x || + cache->scissor.y > y || + cache->scissor.width < width || + cache->scissor.height < height) { + cache->scissor.x = std::min(cache->scissor.x, x); + cache->scissor.y = std::min(cache->scissor.y, y); + cache->scissor.width = std::max(cache->scissor.width, width); + cache->scissor.height = std::max(cache->scissor.height, height); + GL_CHECK(glScissor(cache->scissor.x, cache->scissor.y, cache->scissor.width, cache->scissor.height)); + } +} + void cmdFuncGLES3EndRenderPass(GLES3Device *device) { - static vector drawBuffers; static vector invalidAttachments; - 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; + 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; + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); + GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; invalidAttachments.clear(); @@ -1919,7 +2036,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); + invalidAttachments.push_back(glFramebuffer ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); break; } } @@ -1933,7 +2050,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { case StoreOp::STORE: break; case StoreOp::DISCARD: - invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); + invalidAttachments.push_back(glFramebuffer ? GL_DEPTH_ATTACHMENT : GL_DEPTH); break; } } @@ -1941,25 +2058,26 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { switch (gpuRenderPass->depthStencilAttachment.stencilStoreOp) { case StoreOp::STORE: break; case StoreOp::DISCARD: - invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); + invalidAttachments.push_back(glFramebuffer ? GL_STENCIL_ATTACHMENT : GL_STENCIL); break; } } if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(invalidateTarget, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glInvalidateFramebuffer(invalidateTarget, utils::toUint(invalidAttachments.size()), invalidAttachments.data())); } }; if (instance.resolveMask) { - drawBuffers.clear(); + device->context()->makeCurrent(instance.resolveFramebuffer.swapchain, instance.framebuffer.swapchain); - if (cache->glReadFramebuffer != instance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, instance.glFramebuffer)); - cache->glReadFramebuffer = instance.glFramebuffer; + if (cache->glReadFramebuffer != glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, glFramebuffer)); + cache->glReadFramebuffer = glFramebuffer; } - if (cache->glDrawFramebuffer != instance.glResolveFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, instance.glResolveFramebuffer)); - cache->glDrawFramebuffer = instance.glResolveFramebuffer; + + if (cache->glDrawFramebuffer != glResolveFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glResolveFramebuffer)); + cache->glDrawFramebuffer = glResolveFramebuffer; } if (instance.resolveMask & GL_COLOR_BUFFER_BIT) { @@ -1971,12 +2089,11 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { GLES3GPUTexture *srcTex = gpuFramebuffer->gpuColorTextures[subpass.colors[i]]; GLES3GPUTexture *dstTex = gpuFramebuffer->gpuColorTextures[subpass.resolves[i]]; + ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); 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); } } @@ -1988,6 +2105,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { ? gpuFramebuffer->gpuColorTextures[subpass.depthStencilResolve] : gpuFramebuffer->gpuDepthStencilTexture; + ensureScissorRect(cache, 0, 0, dstTex->width, dstTex->height); GL_CHECK(glBlitFramebuffer( 0, 0, srcTex->width, srcTex->height, 0, 0, dstTex->width, dstTex->height, @@ -2008,6 +2126,8 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { GL_CHECK(glDisable(GL_SHADER_PIXEL_LOCAL_STORAGE_EXT)); cache->isPLSEnabled = false; } + + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers.back().glBarriers, gpuRenderPass->barriers.back().glBarriersByRegion); } else if (gpuFramebuffer->usesFBF) { if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { GL_CHECK(glFramebufferFetchBarrierEXT()); @@ -2022,6 +2142,8 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { performStoreOp(attachmentIndex, glAttachmentIndex++); } performDepthStencilStoreOp(); + + cmdFuncGLES3MemoryBarrier(device, gpuRenderPass->barriers.back().glBarriers, gpuRenderPass->barriers.back().glBarriersByRegion); } } } @@ -2825,9 +2947,6 @@ CC_GLES3_API void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPU auto glType = formatToGLType(gpuTexture->format); for (uint32_t i = 0; i < count; ++i) { auto region = regions[i]; - auto w = region.texExtent.width; - auto h = region.texExtent.height; - auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); uint8_t *copyDst = buffers[i]; auto framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTexture, region.texSubres); if (device->stateCache()->glReadFramebuffer != framebuffer) { @@ -2837,6 +2956,7 @@ CC_GLES3_API void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPU GL_CHECK(glReadPixels(region.texOffset.x, region.texOffset.y, region.texExtent.width, region.texExtent.height, glFormat, glType, copyDst)); } } + void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc, GLES3GPUTexture *gpuTextureDst, const TextureBlit *regions, uint count, Filter filter) { GLES3GPUStateCache *cache = device->stateCache(); @@ -2853,20 +2973,31 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc for (uint i = 0U; i < count; ++i) { const TextureBlit ®ion = regions[i]; - GLuint srcFramebuffer = gpuTextureSrc ? device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrc, region.srcSubres) - : device->constantRegistry()->defaultFramebuffer; + device->context()->makeCurrent(gpuTextureDst->swapchain, gpuTextureSrc->swapchain); + + GLuint srcFramebuffer = 0; + if (gpuTextureSrc->swapchain) { + srcFramebuffer = gpuTextureSrc->swapchain->glFramebuffer; + } else { + srcFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrc, region.srcSubres); + } if (cache->glReadFramebuffer != srcFramebuffer) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFramebuffer)); cache->glReadFramebuffer = srcFramebuffer; } - GLuint dstFramebuffer = gpuTextureDst ? device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst, region.dstSubres) - : device->constantRegistry()->defaultFramebuffer; + GLuint dstFramebuffer = 0; + if (gpuTextureDst->swapchain) { + dstFramebuffer = gpuTextureDst->swapchain->glFramebuffer; + } else { + dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst, region.dstSubres); + } if (cache->glDrawFramebuffer != dstFramebuffer) { GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFramebuffer)); cache->glDrawFramebuffer = dstFramebuffer; } + ensureScissorRect(cache, region.dstOffset.x, region.dstOffset.y, region.dstExtent.width, region.dstExtent.height); GL_CHECK(glBlitFramebuffer( region.srcOffset.x, region.srcOffset.y, diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index 8654b80648..7480c81d13 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -26,7 +26,6 @@ #pragma once #include "GLES3GPUObjects.h" -#include "gfx-base/GFXDef.h" namespace cc { namespace gfx { @@ -51,18 +50,6 @@ public: } }; -enum class GLES3State { - VIEWPORT, - SCISSOR, - LINE_WIDTH, - DEPTH_BIAS, - BLEND_CONSTANTS, - DEPTH_BOUNDS, - STENCIL_WRITE_MASK, - STENCIL_COMPARE_MASK, - COUNT, -}; - class GLES3CmdBindStates final : public GLESCmd { public: GLES3GPUPipelineState * gpuPipelineState = nullptr; @@ -241,6 +228,7 @@ CC_GLES3_API void cmdFuncGLES3CreateInputAssembler(GLES3Device *device, GLES3GPU CC_GLES3_API void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembler *gpuInputAssembler); CC_GLES3_API void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO); CC_GLES3_API void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO); +CC_GLES3_API void cmdFuncGLES3CreateGlobalBarrier(const std::vector &prevAccesses, const std::vector &nextAccesses, GLES3GPUGlobalBarrier *barrier); CC_GLES3_API void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPURenderPass * gpuRenderPass = nullptr, diff --git a/native/cocos/renderer/gfx-gles3/GLES3Context.cpp b/native/cocos/renderer/gfx-gles3/GLES3Context.cpp deleted file mode 100644 index 6ede21cf36..0000000000 --- a/native/cocos/renderer/gfx-gles3/GLES3Context.cpp +++ /dev/null @@ -1,619 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES3Std.h" - -#include "GLES3Context.h" -#include "GLES3Device.h" -#include "GLES3GPUObjects.h" - -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) - #include "android/native_window.h" -#elif CC_PLATFORM == CC_PLATFORM_OHOS - #include - #include -#endif - -#define FORCE_DISABLE_VALIDATION 1 - -namespace cc { -namespace gfx { - -#if CC_DEBUG > 0 && defined(GL_DEBUG_SOURCE_API_KHR) -void GL_APIENTRY GLES3EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { - String sourceDesc; - switch (source) { - case GL_DEBUG_SOURCE_API_KHR: sourceDesc = "API"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: sourceDesc = "SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR: sourceDesc = "WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY_KHR: sourceDesc = "THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION_KHR: sourceDesc = "APPLICATION"; break; - default: sourceDesc = "OTHER"; - } - - String typeDesc; - switch (type) { - case GL_DEBUG_TYPE_ERROR_KHR: typeDesc = "ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: typeDesc = "PEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: typeDesc = "UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PERFORMANCE_KHR: typeDesc = "PERFORMANCE"; break; - case GL_DEBUG_TYPE_PORTABILITY_KHR: typeDesc = "PORTABILITY"; break; - case GL_DEBUG_TYPE_MARKER_KHR: typeDesc = "MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP_KHR: typeDesc = "PUSH_GROUP"; break; - case GL_DEBUG_TYPE_POP_GROUP_KHR: typeDesc = "POP_GROUP"; break; - default: typeDesc = "OTHER"; - } - - String severityDesc; - switch (severity) { - case GL_DEBUG_SEVERITY_HIGH_KHR: severityDesc = "HIGH"; break; - case GL_DEBUG_SEVERITY_MEDIUM_KHR: severityDesc = "MEDIUM"; break; - case GL_DEBUG_SEVERITY_LOW_KHR: severityDesc = "LOW"; break; - default: severityDesc = "NOTIFICATION"; - } - - String msg = StringUtil::format("source: %s, type: %s, severity: %s, message: %s", - sourceDesc.c_str(), typeDesc.c_str(), severityDesc.c_str(), message); - - if (severity == GL_DEBUG_SEVERITY_HIGH_KHR) { - CC_LOG_WARNING(msg.c_str()); - } else { - CC_LOG_DEBUG(msg.c_str()); - } -} -#endif - -GLES3Context::GLES3Context() = default; -GLES3Context::~GLES3Context() = default; - -#if (CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_OHOS) - -bool GLES3Context::doInit(const ContextInfo &info) { - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; - auto *window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - - ////////////////////////////////////////////////////////////////////////// - - if (!info.sharedCtx) { - if (!gles3wInit()) { - return false; - } - - _isPrimaryContex = true; - _windowHandle = info.windowHandle; - - #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) - _nativeDisplay = GetDC(window); - if (!_nativeDisplay) { - return false; - } - - EGL_CHECK(_eglDisplay = eglGetDisplay(_nativeDisplay)); - if (_eglDisplay == EGL_NO_DISPLAY) { - EGL_CHECK(_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); - } - #else - EGL_CHECK(_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); - #endif - - // If a display still couldn't be obtained, return an error. - if (_eglDisplay == EGL_NO_DISPLAY) { - CC_LOG_ERROR("eglGetDisplay() - FAILED."); - return false; - } - - EGLint major = 0; - EGLint minor = 0; - if (eglInitialize(_eglDisplay, &major, &minor) != EGL_TRUE) { - CC_LOG_ERROR("Couldn't initialize EGLDisplay."); - return false; - } - - // Make OpenGL ES the current API. - // EGL needs a way to know that any subsequent EGL calls are going to be affecting OpenGL ES, - // rather than any other API (such as OpenVG). - EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API)); - - _colorFmt = Format::RGBA8; - _depthStencilFmt = Format::D24S8; - - bool msaaEnabled = info.msaaEnabled; - EGLint redSize{8}; - EGLint greenSize{8}; - EGLint blueSize{8}; - EGLint alphaSize{8}; - EGLint depthSize{24}; - EGLint stencilSize{8}; - EGLint sampleBufferSize{msaaEnabled ? EGL_DONT_CARE : 0}; - EGLint sampleSize{msaaEnabled ? EGL_DONT_CARE : 0}; - - EGLint defaultAttribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, - // EGL_BUFFER_SIZE, colorBuffSize, - EGL_BLUE_SIZE, blueSize, - EGL_GREEN_SIZE, greenSize, - EGL_RED_SIZE, redSize, - EGL_ALPHA_SIZE, alphaSize, - EGL_DEPTH_SIZE, depthSize, - EGL_STENCIL_SIZE, stencilSize, - EGL_SAMPLE_BUFFERS, sampleBufferSize, - EGL_SAMPLES, sampleSize, - EGL_NONE}; - - int numConfig = 0; - unsigned int success = false; - EGL_CHECK(success = eglChooseConfig(_eglDisplay, defaultAttribs, nullptr, 0, &numConfig)); - if (success) { - _vecEGLConfig.resize(numConfig); - } else { - CC_LOG_ERROR("Query configuration failed."); - return false; - } - - int count = numConfig; - EGL_CHECK(success = eglChooseConfig(_eglDisplay, defaultAttribs, _vecEGLConfig.data(), count, &numConfig)); - if (success == EGL_FALSE || !numConfig) { - CC_LOG_ERROR("eglChooseConfig configuration failed."); - return false; - } - - EGLint depth{0}; - EGLint stencil{0}; - const uint8_t attrNums = 8; - int params[attrNums] = {0}; - bool matched = false; - const bool qualityPreferred = info.performance == Performance::HIGH_QUALITY; - uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); - - for (int i = 0; i < numConfig; i++) { - int depthValue{0}; - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_RED_SIZE, ¶ms[0]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_GREEN_SIZE, ¶ms[1]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_BLUE_SIZE, ¶ms[2]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_ALPHA_SIZE, ¶ms[3]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_DEPTH_SIZE, ¶ms[4]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_STENCIL_SIZE, ¶ms[5]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_SAMPLE_BUFFERS, ¶ms[6]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_SAMPLES, ¶ms[7]); - eglGetConfigAttrib(_eglDisplay, _vecEGLConfig[i], EGL_DEPTH_ENCODING_NV, &depthValue); - - int bNonLinearDepth = (depthValue == EGL_DEPTH_ENCODING_NONLINEAR_NV) ? 1 : 0; - - /*------------------------------------------ANGLE's priority-----------------------------------------------*/ - // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha - uint64_t currScore{0}; - EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); - currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; - currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; - currScore |= static_cast(std::min(colorScore, 127)) << 17; - currScore |= static_cast(std::min(std::abs(params[4] - depthSize), 63)) << 11; - currScore |= static_cast(std::min(std::abs(1 - bNonLinearDepth), 1)) << 10; - currScore |= static_cast(std::min(std::abs(params[5] - stencilSize), 31)) << 6; - currScore |= static_cast(std::min(std::abs(params[3] - alphaSize), 31)) << 0; - /*------------------------------------------ANGLE's priority-----------------------------------------------*/ - - // if msaaEnabled, sampleBuffers and sampleCount should be greater than 0, until iterate to the last one(can't find). - bool msaaLimit = (msaaEnabled ? (params[6] > 0 && params[7] > 0) : (params[6] == 0 && params[7] == 0)); - // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" - bool filter = (currScore < lastScore) ^ qualityPreferred; - if ((filter && msaaLimit) || (!matched && i == numConfig - 1)) { - _eglConfig = _vecEGLConfig[i]; - depth = params[4]; - stencil = params[5]; - _sampleBuffers = static_cast(params[6]); - _sampleCount = static_cast(params[7]); - lastScore = currScore; - matched = true; - } - } - - // Find a suitable EGLConfig - // eglChooseConfig is provided by EGL to provide an easy way to select an appropriate configuration. It takes in the capabilities - // specified in the attribute list, and returns a list of available configurations that match or exceed the capabilities requested. - // Details of all the possible attributes and how they are selected for by this function are available in the EGL reference pages here: - // http://www.khronos.org/registry/egl/sdk/docs/man/xhtml/eglChooseConfig.html - // It is also possible to simply get the entire list of configurations and use a custom algorithm to choose a suitable one, as many - // advanced applications choose to do. For this application however, taking the first EGLConfig that the function returns suits - // its needs perfectly, so we limit it to returning a single EGLConfig. - - CC_LOG_INFO("Setup EGLConfig: depth [%d] stencil [%d] sampleBuffer [%d] sampleCount [%d]", depth, stencil, _sampleBuffers, _sampleCount); - - if (depth == 16 && stencil == 0) { - _depthStencilFmt = Format::D16; - } else if (depth == 16 && stencil == 8) { - _depthStencilFmt = Format::D16S8; - } else if (depth == 24 && stencil == 0) { - _depthStencilFmt = Format::D24; - } else if (depth == 24 && stencil == 8) { - _depthStencilFmt = Format::D24S8; - } else if (depth == 32 && stencil == 0) { - _depthStencilFmt = Format::D32F; - } else if (depth == 32 && stencil == 8) { - _depthStencilFmt = Format::D32F_S8; - } else { - CC_LOG_ERROR("Unknown depth stencil format."); - return false; - } - - CC_LOG_INFO("Chosen EGLConfig: color [%s], depth stencil [%s].", - GFX_FORMAT_INFOS[static_cast(_colorFmt)].name.c_str(), - GFX_FORMAT_INFOS[static_cast(_depthStencilFmt)].name.c_str()); - - /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is - * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). - * As soon as we picked a EGLConfig, we can safely reconfigure the - * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ - - #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) - - EGLint nFmt; - if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { - CC_LOG_ERROR("Getting configuration attributes failed."); - return false; - } - auto width = static_cast(GLES3Device::getInstance()->getWidth()); - auto height = static_cast(GLES3Device::getInstance()->getHeight()); - - #if CC_PLATFORM == CC_PLATFORM_ANDROID - ANativeWindow_setBuffersGeometry(window, width, height, nFmt); - #elif CC_PLATFORM == CC_PLATFORM_OHOS - NativeLayerHandle(window, NativeLayerOps::SET_WIDTH_AND_HEIGHT, width, height); - NativeLayerHandle(window, NativeLayerOps::SET_FORMAT, nFmt); - #endif - #endif - - EGL_CHECK(_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, window, nullptr)); - if (_eglSurface == EGL_NO_SURFACE) { - auto err = eglGetError(); - CC_LOG_ERROR("Window surface created failed. code %d", err); - return false; - } - - //String eglVendor = eglQueryString(_eglDisplay, EGL_VENDOR); - //String eglVersion = eglQueryString(_eglDisplay, EGL_VERSION); - - EGL_CHECK(_extensions = StringUtil::split(eglQueryString(_eglDisplay, EGL_EXTENSIONS), " ")); - - _majorVersion = 3; - _minorVersion = 0; - EGLint ctxAttribs[32]; - uint n = 0; - - bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); - if (hasKHRCreateCtx) { - for (int m = 2; m >= 0; --m) { - #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - m = 0; // Mac OpenGL doesn't really support ES 3.1+ features - #endif - n = 0; - ctxAttribs[n++] = EGL_CONTEXT_MAJOR_VERSION_KHR; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n++] = EGL_CONTEXT_MINOR_VERSION_KHR; - ctxAttribs[n++] = m; - - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION - ctxAttribs[n++] = EGL_CONTEXT_FLAGS_KHR; - ctxAttribs[n++] = EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - #endif - ctxAttribs[n] = EGL_NONE; - - EGL_CHECK(_eglContext = eglCreateContext(_eglDisplay, _eglConfig, nullptr, ctxAttribs)); - if (_eglContext) { - _minorVersion = m; - break; - } - } - } else { - ctxAttribs[n++] = EGL_CONTEXT_CLIENT_VERSION; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n] = EGL_NONE; - EGL_CHECK(_eglContext = eglCreateContext(_eglDisplay, _eglConfig, nullptr, ctxAttribs)); - } - - if (!_eglContext) { - CC_LOG_ERROR("Create EGL context failed."); - return false; - } - - _eglSharedContext = _eglContext; - - } else { - auto *sharedCtx = static_cast(info.sharedCtx); - - _majorVersion = sharedCtx->majorVer(); - _minorVersion = sharedCtx->minorVer(); - _nativeDisplay = sharedCtx->nativeDisplay(); - _eglDisplay = sharedCtx->eglDisplay(); - _eglConfig = sharedCtx->eglConfig(); - _eglSharedContext = sharedCtx->eglSharedCtx(); - _eglSurface = sharedCtx->eglSurface(); - _colorFmt = sharedCtx->getColorFormat(); - _depthStencilFmt = sharedCtx->getDepthStencilFormat(); - _extensions = sharedCtx->_extensions; - _isInitialized = sharedCtx->_isInitialized; - - bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); - if (!hasKHRCreateCtx) { - CC_LOG_INFO("EGL context creation: EGL_KHR_create_context not supported. Minor version will be discarded, and debug disabled."); - _minorVersion = 0; - } - - EGLint ctxAttribs[32]; - uint n = 0; - - if (hasKHRCreateCtx) { - ctxAttribs[n++] = EGL_CONTEXT_MAJOR_VERSION_KHR; - ctxAttribs[n++] = _majorVersion; - ctxAttribs[n++] = EGL_CONTEXT_MINOR_VERSION_KHR; - ctxAttribs[n++] = _minorVersion; - - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION - ctxAttribs[n++] = EGL_CONTEXT_FLAGS_KHR; - ctxAttribs[n++] = EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - #endif - } else { - ctxAttribs[n++] = EGL_CONTEXT_CLIENT_VERSION; - ctxAttribs[n++] = _majorVersion; - } - - ctxAttribs[n] = EGL_NONE; - - EGL_CHECK(_eglContext = eglCreateContext(_eglDisplay, _eglConfig, _eglSharedContext, ctxAttribs)); - if (!_eglContext) { - CC_LOG_ERROR("Create EGL context with share context [0x%p] failed.", _eglSharedContext); - return false; - } - } - - return true; -} - -void GLES3Context::doDestroy() { - if (_eglDisplay) { - EGL_CHECK(eglMakeCurrent(_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - } - - if (!_vecEGLConfig.empty()) { - _vecEGLConfig.clear(); - } - - if (_eglContext != EGL_NO_CONTEXT) { - EGL_CHECK(eglDestroyContext(_eglDisplay, _eglContext)); - _eglContext = EGL_NO_CONTEXT; - } - - if (_isPrimaryContex) { - if (_eglSurface != EGL_NO_SURFACE) { - EGL_CHECK(eglDestroySurface(_eglDisplay, _eglSurface)); - _eglSurface = EGL_NO_SURFACE; - } - - if (_eglDisplay != EGL_NO_DISPLAY) { - EGL_CHECK(eglTerminate(_eglDisplay)); - _eglDisplay = EGL_NO_DISPLAY; - } - - #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) - if (_nativeDisplay) { - ReleaseDC(reinterpret_cast(_windowHandle), _nativeDisplay); - } - #endif - } - - _isPrimaryContex = false; - _windowHandle = 0; - _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues - _vsyncMode = VsyncMode::OFF; - _isInitialized = false; -} - -void GLES3Context::releaseSurface(uintptr_t /*windowHandle*/) { - #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) - if (_eglSurface != EGL_NO_SURFACE) { - eglDestroySurface(_eglDisplay, _eglSurface); - EGL_CHECK(eglMakeCurrent(_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - _eglSurface = EGL_NO_SURFACE; - } - #endif -} - -void GLES3Context::acquireSurface(uintptr_t windowHandle) { - #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) - { - _windowHandle = windowHandle; - auto *window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - - EGLint nFmt = 0; - if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { - CC_LOG_ERROR("Getting configuration attributes failed."); - return; - } - - // Device's size will be updated after recreate window (in resize event) and is incorrect for now. - #if CC_PLATFORM == CC_PLATFORM_ANDROID - int32_t width = ANativeWindow_getWidth(window); - int32_t height = ANativeWindow_getHeight(window); - ANativeWindow_setBuffersGeometry(window, width, height, nFmt); - #elif CC_PLATFORM == CC_PLATFORM_OHOS - int32_t width = NativeLayerHandle(window, NativeLayerOps::GET_WIDTH); - int32_t height = NativeLayerHandle(window, NativeLayerOps::GET_HEIGHT); - #endif - GLES3Device::getInstance()->resize(width, height); - - EGL_CHECK(_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, window, nullptr)); - if (_eglSurface == EGL_NO_SURFACE) { - CC_LOG_ERROR("Recreate window surface failed."); - return; - } - - static_cast(GLES3Device::getInstance()->getContext())->makeCurrent(); - GLES3Device::getInstance()->stateCache()->reset(); - } - #endif -} - -bool GLES3Context::makeCurrentImpl(bool bound) { - bool succeeded; - EGL_CHECK(succeeded = eglMakeCurrent(_eglDisplay, - bound ? _eglSurface : EGL_NO_SURFACE, - bound ? _eglSurface : EGL_NO_SURFACE, - bound ? _eglContext : EGL_NO_CONTEXT)); - return succeeded; -} - -void GLES3Context::present() { - EGL_CHECK(eglSwapBuffers(_eglDisplay, _eglSurface)); -} - -#endif - -bool GLES3Context::makeCurrent(bool bound) { - if (!bound) { - CC_LOG_DEBUG("eglMakeCurrent() - UNBOUNDED, Context: 0x%p", this); - return makeCurrentImpl(false); - } - - if (makeCurrentImpl(bound)) { -#if (CC_PLATFORM != CC_PLATFORM_MAC_IOS) - if (!_isInitialized) { - // Turn on or off the vertical sync depending on the input bool value. - int interval = 1; - switch (_vsyncMode) { - case VsyncMode::OFF: interval = 0; break; - case VsyncMode::ON: - case VsyncMode::RELAXED: interval = 1; break; - case VsyncMode::MAILBOX: interval = 0; break; - case VsyncMode::HALF: interval = 2; break; - default: break; - } - - if (eglSwapInterval(_eglDisplay, interval) != 1) { - CC_LOG_ERROR("wglSwapInterval() - FAILED."); - return false; - } - _isInitialized = true; - } - - #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION - GL_CHECK(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR)); - if (glDebugMessageControlKHR) { - GL_CHECK(glDebugMessageControlKHR(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE)); - } - if (glDebugMessageCallbackKHR) { - GL_CHECK(glDebugMessageCallbackKHR(GLES3EGLDebugProc, NULL)); - } - #endif - -#endif - - ////////////////////////////////////////////////////////////////////////// - - GL_CHECK(glPixelStorei(GL_PACK_ALIGNMENT, 1)); - GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - GL_CHECK(glActiveTexture(GL_TEXTURE0)); - - ////////////////////////////////////////////////////////////////////////// - - GL_CHECK(glEnable(GL_SCISSOR_TEST)); - GL_CHECK(glEnable(GL_CULL_FACE)); - GL_CHECK(glCullFace(GL_BACK)); - - GL_CHECK(glFrontFace(GL_CCW)); - - GL_CHECK(glDisable(GL_SAMPLE_COVERAGE)); - - ////////////////////////////////////////////////////////////////////////// - // DepthStencilState - GL_CHECK(glEnable(GL_DEPTH_TEST)); - GL_CHECK(glDepthMask(GL_TRUE)); - GL_CHECK(glDepthFunc(GL_LESS)); - - GL_CHECK(glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xffffffff)); - GL_CHECK(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP)); - GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); - GL_CHECK(glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 1, 0xffffffff)); - GL_CHECK(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP)); - GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); - - GL_CHECK(glDisable(GL_STENCIL_TEST)); - - ////////////////////////////////////////////////////////////////////////// - // BlendState - - GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE)); - GL_CHECK(glDisable(GL_BLEND)); - GL_CHECK(glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD)); - GL_CHECK(glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO)); - GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); - GL_CHECK(glBlendColor(0.0F, 0.0F, 0.0F, 0.0F)); - - GL_CHECK(glUseProgram(0)); - - GL_CHECK(glBindVertexArray(0)); - - GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_COPY_READ_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_COPY_WRITE_BUFFER, 0)); - - if (_minorVersion) { - GL_CHECK(glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0)); - GL_CHECK(glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)); - } - - GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_3D, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0)); - - GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)); - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - if (GLES3Device::getInstance()->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { - GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); - } - - CC_LOG_DEBUG("eglMakeCurrent() - SUCCEEDED, Context: 0x%p", this); - return true; - } - CC_LOG_ERROR("MakeCurrent() - FAILED, Context: 0x%p", this); - return false; -} - -bool GLES3Context::checkExtension(const String &extension) const { - return (std::find(_extensions.begin(), _extensions.end(), extension) != _extensions.end()); -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Context.h b/native/cocos/renderer/gfx-gles3/GLES3Context.h deleted file mode 100644 index b48c860861..0000000000 --- a/native/cocos/renderer/gfx-gles3/GLES3Context.h +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include -#include "GLES3Std.h" -#include "GLES3Wrangler.h" -#include "gfx-base/GFXContext.h" - -namespace cc { -namespace gfx { - -class CC_GLES3_API GLES3Context final : public Context { -public: - GLES3Context(); - ~GLES3Context() override; - - void present() override; - - bool makeCurrent(bool bound); - bool checkExtension(const String &extension) const; - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - inline intptr_t eagl_context() const { return _eaglContext; } - inline intptr_t eagl_shared_ctx() const { return _eaglSharedContext; } -#else - inline NativeDisplayType nativeDisplay() const { return _nativeDisplay; } - inline EGLDisplay eglDisplay() const { return _eglDisplay; } - inline EGLConfig eglConfig() const { return _eglConfig; } - inline EGLSurface eglSurface() const { return _eglSurface; } - inline EGLContext eglContext() const { return _eglContext; } - inline EGLContext eglSharedCtx() const { return _eglSharedContext; } -#endif - inline bool makeCurrent() { return makeCurrent(true); } - 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); - -protected: - bool makeCurrentImpl(bool bound); -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - bool createCustomFrameBuffer(); - void doDestroyCustomFrameBuffer(); -#endif - - bool doInit(const ContextInfo &info) override; - void doDestroy() override; - - bool _isPrimaryContex = false; - 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 _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; -#endif - int _majorVersion = 0; - int _minorVersion = 0; - StringArray _extensions; -}; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Context.mm b/native/cocos/renderer/gfx-gles3/GLES3Context.mm deleted file mode 100644 index 52a4c1cc54..0000000000 --- a/native/cocos/renderer/gfx-gles3/GLES3Context.mm +++ /dev/null @@ -1,225 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES3Std.h" -#include "GLES3Context.h" - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - -#import - -namespace cc { -namespace gfx { - -bool GLES3Context::doInit(const ContextInfo &info) { - - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; - - ////////////////////////////////////////////////////////////////////////// - - if (!info.sharedCtx) { - _isPrimaryContex = true; - _windowHandle = info.windowHandle; - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)( ((UIView*)(_windowHandle)).layer); - eaglLayer.opaque = TRUE; - - EAGLContext* eagl_context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES3]; - if (!eagl_context) { - CC_LOG_ERROR("Create EAGL context failed."); - return false; - } - - _eaglContext = (intptr_t)eagl_context; - _eaglSharedContext = (intptr_t)eagl_context; - _majorVersion = 3; - - if (!gles3wInit()) { - return false; - } - - } else { - GLES3Context* sharedCtx = (GLES3Context*)info.sharedCtx; - _majorVersion = sharedCtx->_majorVersion; - _defaultFBO = sharedCtx->_defaultFBO; - _defaultColorBuffer = sharedCtx->_defaultColorBuffer; - _defaultDepthStencilBuffer = sharedCtx->_defaultDepthStencilBuffer; - - EAGLContext* eagl_shared_context = (EAGLContext*)sharedCtx->eagl_shared_ctx(); - EAGLContext* eagl_context = [[EAGLContext alloc] initWithAPI: [eagl_shared_context API] sharegroup: [eagl_shared_context sharegroup]]; - if (!eagl_context) { - CC_LOG_ERROR("Create EGL context with share context [0x%p] failed.", eagl_shared_context); - return false; - } - - _eaglContext = (intptr_t)eagl_context; - _eaglSharedContext = (intptr_t)eagl_shared_context; - } - - _colorFmt = Format::RGBA8; - _depthStencilFmt = Format::D24S8; - - return true; -} - -bool GLES3Context::createCustomFrameBuffer() -{ - if (_defaultFBO) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO)); - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer)); - return true; - } - - GL_CHECK(glGenFramebuffers(1, &_defaultFBO)); - if (0 == _defaultFBO) - { - CC_LOG_ERROR("Can not create default frame buffer"); - return false; - } - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO)); - - GL_CHECK(glGenRenderbuffers(1, &_defaultColorBuffer)); - if (0 == _defaultColorBuffer) - { - CC_LOG_ERROR("Can not create default color buffer"); - return false; - } - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer)); - - CAEAGLLayer* eaglLayer = (CAEAGLLayer*)( ((UIView*)(_windowHandle)).layer); - if (! [(EAGLContext*)_eaglContext renderbufferStorage:GL_RENDERBUFFER - fromDrawable:eaglLayer]) - { - CC_LOG_ERROR("Attaches EAGLDrawable as storage for the OpenGL ES renderbuffer object failed."); - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0)); - GL_CHECK(glDeleteRenderbuffers(1, &_defaultColorBuffer)); - return false; - } - - GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _defaultColorBuffer)); - - GLint framebufferWidth = 0, framebufferHeight = 0; - GL_CHECK(glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth)); - GL_CHECK(glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight)); - - GL_CHECK(glGenRenderbuffers(1, &_defaultDepthStencilBuffer)); - if (_defaultDepthStencilBuffer == 0) - { - // Application can run without depth/stencil buffer, so don't return false here. - CC_LOG_ERROR("Can not create default depth/stencil buffer"); - } - - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, _defaultDepthStencilBuffer)); - GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, framebufferWidth, framebufferHeight)); - GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthStencilBuffer)); - GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthStencilBuffer)); - - 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:; - } - doDestroyCustomFrameBuffer(); - return false; - } - - GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer)); - return true; -} - -void GLES3Context::doDestroyCustomFrameBuffer() { - if (_defaultColorBuffer) { - GL_CHECK(glDeleteRenderbuffers(1, &_defaultColorBuffer)); - _defaultColorBuffer = 0; - } - if (_defaultDepthStencilBuffer) { - GL_CHECK(glDeleteRenderbuffers(1, &_defaultDepthStencilBuffer)); - _defaultDepthStencilBuffer = 0; - } - - if (_defaultFBO) { - GL_CHECK(glDeleteFramebuffers(1, &_defaultFBO)); - _defaultFBO = 0; - } -} - -void GLES3Context::doDestroy() { - doDestroyCustomFrameBuffer(); - - if (_eaglContext) { - [(EAGLContext*)_eaglContext release]; - } - - _isPrimaryContex = false; - _windowHandle = 0; - _vsyncMode = VsyncMode::OFF; - _isInitialized = false; -} - -void GLES3Context::present() { - if (! [(EAGLContext*)_eaglContext presentRenderbuffer:GL_RENDERBUFFER] ) { - CC_LOG_ERROR("Failed to present content."); - } -} - -bool GLES3Context::makeCurrentImpl(bool bound) { - if (!bound) return [EAGLContext setCurrentContext: nil]; - return [EAGLContext setCurrentContext: (EAGLContext*)_eaglContext] && createCustomFrameBuffer(); -} - -void GLES3Context::releaseSurface(uintptr_t /*windowHandle*/) { -} - -void GLES3Context::acquireSurface(uintptr_t /*windowHandle*/) { -} - -} // namespace gfx -} // namespace cc - -#endif diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp index d384342f3b..e23bfeb983 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp @@ -29,8 +29,8 @@ #include "GLES3Commands.h" #include "GLES3DescriptorSet.h" #include "GLES3DescriptorSetLayout.h" -#include "GLES3Sampler.h" #include "GLES3Texture.h" +#include "states/GLES3Sampler.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.h b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.h index 78df06862f..bb6edec95a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.h +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES3_DESCRIPTOR_SET_H_ -#define CC_GFXGLES3_DESCRIPTOR_SET_H_ +#pragma once +#include "GLES3Std.h" #include "gfx-base/GFXDescriptorSet.h" namespace cc { @@ -36,7 +36,7 @@ class GLES3GPUDescriptorSet; class CC_GLES3_API GLES3DescriptorSet final : public DescriptorSet { public: GLES3DescriptorSet(); - ~GLES3DescriptorSet(); + ~GLES3DescriptorSet() override; void update() override; @@ -51,5 +51,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES3_DESCRIPTOR_SET_H_ diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.h b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.h index c309b71de2..b99e8d729a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES3_DESCRIPTOR_SET_LAYOUT_H_ -#define CC_GFXGLES3_DESCRIPTOR_SET_LAYOUT_H_ +#pragma once +#include "GLES3Std.h" #include "gfx-base/GFXDescriptorSetLayout.h" namespace cc { @@ -36,7 +36,7 @@ class GLES3GPUDescriptorSetLayout; class CC_GLES3_API GLES3DescriptorSetLayout final : public DescriptorSetLayout { public: GLES3DescriptorSetLayout(); - ~GLES3DescriptorSetLayout(); + ~GLES3DescriptorSetLayout() override; inline GLES3GPUDescriptorSetLayout *gpuDescriptorSetLayout() const { return _gpuDescriptorSetLayout; } @@ -49,5 +49,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES3_DESCRIPTOR_SET_LAYOUT_H_ diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index a7ed159278..60e2a0305a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -27,23 +27,23 @@ #include "GLES3Buffer.h" #include "GLES3CommandBuffer.h" -#include "GLES3Context.h" +#include "GLES3Commands.h" #include "GLES3DescriptorSet.h" #include "GLES3DescriptorSetLayout.h" #include "GLES3Device.h" #include "GLES3Framebuffer.h" -#include "GLES3GlobalBarrier.h" +#include "GLES3GPUObjects.h" #include "GLES3InputAssembler.h" #include "GLES3PipelineLayout.h" #include "GLES3PipelineState.h" #include "GLES3PrimaryCommandBuffer.h" #include "GLES3Queue.h" #include "GLES3RenderPass.h" -#include "GLES3Sampler.h" #include "GLES3Shader.h" +#include "GLES3Swapchain.h" #include "GLES3Texture.h" -#include "base/Utils.h" -#include "gfx-gles-common/GLESCommandPool.h" +#include "states/GLES3GlobalBarrier.h" +#include "states/GLES3Sampler.h" // when capturing GLES commands (RENDERDOC_HOOK_EGL=1, default value) // renderdoc doesn't support this extension during replay @@ -69,17 +69,16 @@ GLES3Device::~GLES3Device() { GLES3Device::instance = nullptr; } -bool GLES3Device::doInit(const DeviceInfo &info) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - ctxInfo.msaaEnabled = info.isAntiAlias; - ctxInfo.performance = Performance::HIGH_QUALITY; +bool GLES3Device::doInit(const DeviceInfo & /*info*/) { + _gpuContext = CC_NEW(GLES3GPUContext); + _gpuStateCache = CC_NEW(GLES3GPUStateCache); + _gpuConstantRegistry = CC_NEW(GLES3GPUConstantRegistry); + _gpuFramebufferCacheMap = CC_NEW(GLES3GPUFramebufferCacheMap(_gpuStateCache)); - _renderContext = CC_NEW(GLES3Context); - if (!_renderContext->initialize(ctxInfo)) { + if (!_gpuContext->initialize(_gpuStateCache, _gpuConstantRegistry)) { destroy(); return false; - } + }; QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; @@ -90,13 +89,6 @@ bool GLES3Device::doInit(const DeviceInfo &info) { cmdBuffInfo.queue = _queue; _cmdBuff = createCommandBuffer(cmdBuffInfo); - _gpuStateCache = CC_NEW(GLES3GPUStateCache); - _gpuStagingBufferPool = CC_NEW(GLES3GPUStagingBufferPool); - _gpuConstantRegistry = CC_NEW(GLES3GPUConstantRegistry); - _gpuFramebufferCacheMap = CC_NEW(GLES3GPUFramebufferCacheMap(_gpuStateCache)); - - bindRenderContext(true); - String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); @@ -110,8 +102,7 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _features[toNumber(Feature::BLEND_MINMAX)] = true; _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; - uint minorVersion = static_cast(_context)->minorVer(); - if (minorVersion) { + if (_gpuConstantRegistry->glMinorVersion) { _features[toNumber(Feature::COMPUTE_SHADER)] = true; } @@ -135,17 +126,9 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _features[toNumber(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"; + // PVRVFrame has issues on their support +#if CC_PLATFORM != CC_PLATFORM_WINDOWS if (checkExtension("framebuffer_fetch")) { String nonCoherent = "framebuffer_fetch_non"; @@ -169,8 +152,6 @@ bool GLES3Device::doInit(const DeviceInfo &info) { } } - // PVRVFrame has issues on their PLS support -#if CC_PLATFORM != CC_PLATFORM_WINDOWS && CC_PLATFORM != CC_PLATFORM_MAC_OSX if (checkExtension("pixel_local_storage")) { if (checkExtension("pixel_local_storage2")) { _gpuConstantRegistry->mPLS = PLSSupportLevel::LEVEL2; @@ -181,8 +162,15 @@ bool GLES3Device::doInit(const DeviceInfo &info) { } #endif - _gpuConstantRegistry->glMinorVersion = _renderContext->minorVer(); - _gpuConstantRegistry->defaultFramebuffer = _renderContext->getDefaultFramebuffer(); +#if CC_PLATFORM != CC_PLATFORM_WINDOWS || 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 compressedFmts; @@ -209,15 +197,6 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _vendor = reinterpret_cast(glGetString(GL_VENDOR)); _version = reinterpret_cast(glGetString(GL_VERSION)); - CC_LOG_INFO("GLES3 device initialized."); - CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); - CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); - 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", _gpuConstantRegistry->mPLS, _gpuConstantRegistry->mPLSsize); - CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); - glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast(&_caps.maxVertexAttributes)); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxVertexUniformVectors)); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxFragmentUniformVectors)); @@ -229,10 +208,8 @@ bool GLES3Device::doInit(const DeviceInfo &info) { glGetIntegerv(GL_MAX_TEXTURE_SIZE, reinterpret_cast(&_caps.maxTextureSize)); glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, reinterpret_cast(&_caps.maxCubeMapTextureSize)); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, reinterpret_cast(&_caps.uboOffsetAlignment)); - glGetIntegerv(GL_DEPTH_BITS, reinterpret_cast(&_caps.depthBits)); - glGetIntegerv(GL_STENCIL_BITS, reinterpret_cast(&_caps.stencilBits)); - if (minorVersion) { + if (_gpuConstantRegistry->glMinorVersion) { glGetIntegerv(GL_MAX_IMAGE_UNITS, reinterpret_cast(&_caps.maxImageUnits)); glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, reinterpret_cast(&_caps.maxShaderStorageBlockSize)); glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, reinterpret_cast(&_caps.maxShaderStorageBufferBindings)); @@ -248,13 +225,20 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxImageUnits, _caps.maxUniformBufferBindings, _caps.maxShaderStorageBufferBindings, _caps.maxVertexAttributes); + CC_LOG_INFO("GLES3 device initialized."); + CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); + CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); + CC_LOG_INFO("VERSION: %s", _version.c_str()); + CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); + CC_LOG_INFO("PIXEL_LOCAL_STORAGE: level %d, size %d", _gpuConstantRegistry->mPLS, _gpuConstantRegistry->mPLSsize); + CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + return true; } void GLES3Device::doDestroy() { CC_SAFE_DELETE(_gpuFramebufferCacheMap) CC_SAFE_DELETE(_gpuConstantRegistry) - CC_SAFE_DELETE(_gpuStagingBufferPool) CC_SAFE_DELETE(_gpuStateCache) CCASSERT(!_memoryStatus.bufferSize, "Buffer memory leaked"); @@ -262,25 +246,14 @@ void GLES3Device::doDestroy() { CC_SAFE_DESTROY(_cmdBuff) CC_SAFE_DESTROY(_queue) - CC_SAFE_DESTROY(_deviceContext) - CC_SAFE_DESTROY(_renderContext) + CC_SAFE_DESTROY(_gpuContext) } -void GLES3Device::releaseSurface(const uintptr_t windowHandle) { - static_cast(_context)->releaseSurface(windowHandle); -} - -void GLES3Device::acquireSurface(const uintptr_t windowHandle) { - static_cast(_context)->acquireSurface(windowHandle); -} - -void GLES3Device::resize(uint width, uint height) { - _width = width; - _height = height; -} - -void GLES3Device::acquire() { - _gpuStagingBufferPool->reset(); +void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { + _swapchains.clear(); + for (uint32_t i = 0; i < count; ++i) { + _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); + } } void GLES3Device::present() { @@ -289,7 +262,9 @@ void GLES3Device::present() { _numInstances = queue->_numInstances; _numTriangles = queue->_numTriangles; - _context->present(); + for (auto *swapchain : _swapchains) { + _gpuContext->present(swapchain); + } // Clear queue stats queue->_numDrawCalls = 0; @@ -297,32 +272,8 @@ void GLES3Device::present() { queue->_numTriangles = 0; } -void GLES3Device::bindRenderContext(bool bound) { - _renderContext->makeCurrent(bound); - _context = bound ? _renderContext : nullptr; - - if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); - _gpuStateCache->reset(); - } -} - -void GLES3Device::bindDeviceContext(bool bound) { - if (!_deviceContext) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - ctxInfo.sharedCtx = _renderContext; - - _deviceContext = CC_NEW(GLES3Context); - _deviceContext->initialize(ctxInfo); - } - _deviceContext->makeCurrent(bound); - _context = bound ? _deviceContext : nullptr; - - if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); - _gpuStateCache->reset(); - } +void GLES3Device::bindContext(bool bound) { + _gpuContext->bindContext(bound); } CommandBuffer *GLES3Device::createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) { @@ -334,6 +285,10 @@ Queue *GLES3Device::createQueue() { return CC_NEW(GLES3Queue); } +Swapchain *GLES3Device::createSwapchain() { + return CC_NEW(GLES3Swapchain); +} + Buffer *GLES3Device::createBuffer() { return CC_NEW(GLES3Buffer); } @@ -342,10 +297,6 @@ Texture *GLES3Device::createTexture() { return CC_NEW(GLES3Texture); } -Sampler *GLES3Device::createSampler() { - return CC_NEW(GLES3Sampler); -} - Shader *GLES3Device::createShader() { return CC_NEW(GLES3Shader); } @@ -378,12 +329,16 @@ PipelineState *GLES3Device::createPipelineState() { return CC_NEW(GLES3PipelineState); } -GlobalBarrier *GLES3Device::createGlobalBarrier() { - return CC_NEW(GLES3GlobalBarrier); +Sampler *GLES3Device::createSampler(const SamplerInfo &info) { + return CC_NEW(GLES3Sampler(info)); } -TextureBarrier *GLES3Device::createTextureBarrier() { - return CC_NEW(TextureBarrier); +GlobalBarrier *GLES3Device::createGlobalBarrier(const GlobalBarrierInfo &info) { + return CC_NEW(GLES3GlobalBarrier(info)); +} + +TextureBarrier *GLES3Device::createTextureBarrier(const TextureBarrierInfo &info) { + return CC_NEW(TextureBarrier(info)); } void GLES3Device::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { @@ -391,7 +346,7 @@ void GLES3Device::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d } void GLES3Device::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count) { - cmdFuncGLES3CopyTextureToBuffers(this, srcTexture ? static_cast(srcTexture)->gpuTexture() : nullptr, buffers, regions, count); + cmdFuncGLES3CopyTextureToBuffers(this, static_cast(srcTexture)->gpuTexture(), buffers, regions, count); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 306789a780..fe052c67cd 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -31,9 +31,9 @@ namespace cc { namespace gfx { -class GLES3Context; +class GLES3GPUContext; +class GLES3GPUSwapchain; class GLES3GPUStateCache; -class GLES3GPUStagingBufferPool; class GLES3GPUFramebufferCacheMap; class GLES3GPUConstantRegistry; @@ -57,15 +57,15 @@ public: using Device::createRenderPass; using Device::createSampler; using Device::createShader; + using Device::createSwapchain; using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; + inline GLES3GPUContext * context() const { return _gpuContext; } inline GLES3GPUStateCache * stateCache() const { return _gpuStateCache; } - inline GLES3GPUStagingBufferPool * stagingBufferPool() const { return _gpuStagingBufferPool; } inline GLES3GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } inline GLES3GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } @@ -79,7 +79,6 @@ protected: static GLES3Device *instance; friend class DeviceManager; - friend class GLES3Context; GLES3Device(); @@ -87,9 +86,9 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -98,23 +97,22 @@ protected: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; - void releaseSurface(uintptr_t windowHandle) override; - void acquireSurface(uintptr_t windowHandle) override; + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; - void bindRenderContext(bool bound) override; - void bindDeviceContext(bool bound) override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; - GLES3Context * _renderContext = nullptr; - GLES3Context * _deviceContext = nullptr; - GLES3GPUStateCache * _gpuStateCache = nullptr; - GLES3GPUStagingBufferPool * _gpuStagingBufferPool = nullptr; - GLES3GPUConstantRegistry * _gpuConstantRegistry = nullptr; - GLES3GPUFramebufferCacheMap *_gpuFramebufferCacheMap = nullptr; + void bindContext(bool bound) override; + + GLES3GPUStateCache * _gpuStateCache{nullptr}; + GLES3GPUContext * _gpuContext{nullptr}; + GLES3GPUConstantRegistry * _gpuConstantRegistry{nullptr}; + GLES3GPUFramebufferCacheMap *_gpuFramebufferCacheMap{nullptr}; + + vector _swapchains; StringArray _extensions; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h index ca0941ddda..30dac5e3de 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXFramebuffer.h" namespace cc { @@ -35,7 +36,7 @@ class GLES3GPUFramebuffer; class CC_GLES3_API GLES3Framebuffer final : public Framebuffer { public: GLES3Framebuffer(); - ~GLES3Framebuffer(); + ~GLES3Framebuffer() override; inline GLES3GPUFramebuffer *gpuFBO() const { return _gpuFBO; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp new file mode 100644 index 0000000000..5dc879aaf3 --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -0,0 +1,422 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GLES3GPUObjects.h" + +#define FORCE_DISABLE_VALIDATION 1 + +namespace cc { +namespace gfx { + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION +constexpr uint DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled + +void GL_APIENTRY GLES3EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { + String sourceDesc; + switch (source) { + case GL_DEBUG_SOURCE_API_KHR: sourceDesc = "API"; break; + case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: sourceDesc = "SHADER_COMPILER"; break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR: sourceDesc = "WINDOW_SYSTEM"; break; + case GL_DEBUG_SOURCE_THIRD_PARTY_KHR: sourceDesc = "THIRD_PARTY"; break; + case GL_DEBUG_SOURCE_APPLICATION_KHR: sourceDesc = "APPLICATION"; break; + default: sourceDesc = "OTHER"; + } + + String typeDesc; + switch (type) { + case GL_DEBUG_TYPE_ERROR_KHR: typeDesc = "ERROR"; break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: typeDesc = "PEPRECATED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: typeDesc = "UNDEFINED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_PERFORMANCE_KHR: typeDesc = "PERFORMANCE"; break; + case GL_DEBUG_TYPE_PORTABILITY_KHR: typeDesc = "PORTABILITY"; break; + case GL_DEBUG_TYPE_MARKER_KHR: typeDesc = "MARKER"; break; + case GL_DEBUG_TYPE_PUSH_GROUP_KHR: typeDesc = "PUSH_GROUP"; break; + case GL_DEBUG_TYPE_POP_GROUP_KHR: typeDesc = "POP_GROUP"; break; + default: typeDesc = "OTHER"; + } + + String severityDesc; + switch (severity) { + case GL_DEBUG_SEVERITY_HIGH_KHR: severityDesc = "HIGH"; break; + case GL_DEBUG_SEVERITY_MEDIUM_KHR: severityDesc = "MEDIUM"; break; + case GL_DEBUG_SEVERITY_LOW_KHR: severityDesc = "LOW"; break; + default: severityDesc = "NOTIFICATION"; + } + + String msg = StringUtil::format("source: %s, type: %s, severity: %s, message: %s", + sourceDesc.c_str(), typeDesc.c_str(), severityDesc.c_str(), message); + + if (severity == GL_DEBUG_SEVERITY_HIGH_KHR) { + CC_LOG_ERROR(msg.c_str()); + CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); + } else if (severity == GL_DEBUG_SEVERITY_MEDIUM_KHR) { + CC_LOG_WARNING(msg.c_str()); + } else { + CC_LOG_DEBUG(msg.c_str()); + } +} +#endif + +bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstantRegistry *constantRegistry) { + _stateCache = stateCache; + _constantRegistry = constantRegistry; + + if (!gles3wInit()) { + return false; + } + + EGL_CHECK(eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY)); + + if (eglDisplay == EGL_NO_DISPLAY) { + CC_LOG_ERROR("eglGetDisplay() - FAILED."); + return false; + } + + EGLBoolean success{false}; + EGL_CHECK(success = eglInitialize(eglDisplay, &eglMajorVersion, &eglMinorVersion)); + + if (!success) { + CC_LOG_ERROR("eglInitialize() - FAILED."); + return false; + } + + EGL_CHECK(eglBindAPI(EGL_OPENGL_ES_API)); + + bool msaaEnabled{false}; + bool qualityPreferred{false}; + + EGLint redSize{8}; + EGLint greenSize{8}; + EGLint blueSize{8}; + EGLint alphaSize{8}; + EGLint depthSize{24}; + EGLint stencilSize{8}; + EGLint sampleBufferSize{msaaEnabled ? EGL_DONT_CARE : 0}; + EGLint sampleSize{msaaEnabled ? EGL_DONT_CARE : 0}; + + EGLint defaultAttribs[]{ + EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, + EGL_BLUE_SIZE, blueSize, + EGL_GREEN_SIZE, greenSize, + EGL_RED_SIZE, redSize, + EGL_ALPHA_SIZE, alphaSize, + EGL_DEPTH_SIZE, depthSize, + EGL_STENCIL_SIZE, stencilSize, + EGL_SAMPLE_BUFFERS, sampleBufferSize, + EGL_SAMPLES, sampleSize, + EGL_NONE}; + + int numConfig{0}; + vector eglConfigs; + + EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, nullptr, 0, &numConfig)); + if (success) { + eglConfigs.resize(numConfig); + } else { + CC_LOG_ERROR("Query configuration failed."); + return false; + } + + int count = numConfig; + EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, eglConfigs.data(), count, &numConfig)); + if (!success || !numConfig) { + CC_LOG_ERROR("eglChooseConfig configuration failed."); + return false; + } + + EGLint depth{0}; + EGLint stencil{0}; + EGLint sampleBuffers{0}; + EGLint sampleCount{0}; + EGLint params[8]{0}; + uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); + + for (int i = 0; i < numConfig; i++) { + int depthValue{0}; + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_RED_SIZE, ¶ms[0]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_GREEN_SIZE, ¶ms[1]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_BLUE_SIZE, ¶ms[2]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_ALPHA_SIZE, ¶ms[3]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_DEPTH_SIZE, ¶ms[4]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_STENCIL_SIZE, ¶ms[5]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_SAMPLE_BUFFERS, ¶ms[6]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_SAMPLES, ¶ms[7]); + eglGetConfigAttrib(eglDisplay, eglConfigs[i], EGL_DEPTH_ENCODING_NV, &depthValue); + + int bNonLinearDepth = (depthValue == EGL_DEPTH_ENCODING_NONLINEAR_NV) ? 1 : 0; + + /*------------------------------------------ANGLE's priority-----------------------------------------------*/ + // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha + uint64_t currScore{0}; + EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); + currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; + currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; + currScore |= static_cast(std::min(colorScore, 127)) << 17; + currScore |= static_cast(std::min(std::abs(params[4] - depthSize), 63)) << 11; + currScore |= static_cast(std::min(std::abs(1 - bNonLinearDepth), 1)) << 10; + currScore |= static_cast(std::min(std::abs(params[5] - stencilSize), 31)) << 6; + currScore |= static_cast(std::min(std::abs(params[3] - alphaSize), 31)) << 0; + /*------------------------------------------ANGLE's priority-----------------------------------------------*/ + + // if msaaEnabled, sampleBuffers and sampleCount should be greater than 0, until iterate to the last one(can't find). + bool msaaLimit = (msaaEnabled ? (params[6] > 0 && params[7] > 0) : (params[6] == 0 && params[7] == 0)); + // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" + bool filter = (currScore < lastScore) ^ qualityPreferred; + if ((filter && msaaLimit) || (!eglConfig && i == numConfig - 1)) { + eglConfig = eglConfigs[i]; + depth = params[4]; + stencil = params[5]; + sampleBuffers = params[6]; + sampleCount = params[7]; + lastScore = currScore; + } + } + + CC_LOG_INFO("Setup EGLConfig: depth [%d] stencil [%d] sampleBuffer [%d] sampleCount [%d]", depth, stencil, sampleBuffers, sampleCount); + + EGL_CHECK(_extensions = StringUtil::split(eglQueryString(eglDisplay, EGL_EXTENSIONS), " ")); + + bool hasKHRCreateCtx = checkExtension(CC_TOSTR(EGL_KHR_create_context)); + if (hasKHRCreateCtx) { + eglAttributes.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR); + eglAttributes.push_back(3); + eglAttributes.push_back(EGL_CONTEXT_MINOR_VERSION_KHR); + eglAttributes.push_back(2); +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION + eglAttributes.push_back(EGL_CONTEXT_FLAGS_KHR); + eglAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR); +#endif + eglAttributes.push_back(EGL_NONE); + + for (int m = 2; m >= 0; --m) { + eglAttributes[3] = m; + EGL_CHECK(eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data())); + if (eglDefaultContext) { + _constantRegistry->glMinorVersion = m; + break; + } + } + } else { + eglAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION); + eglAttributes.push_back(3); + eglAttributes.push_back(EGL_NONE); + + EGL_CHECK(eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data())); + } + + if (!eglDefaultContext) { + CC_LOG_ERROR("Create EGL context failed."); + return false; + } + + EGLint pbufferAttribs[]{ + EGL_WIDTH, 1, + EGL_HEIGHT, 1, + EGL_NONE}; + EGL_CHECK(eglDefaultSurface = eglCreatePbufferSurface(eglDisplay, eglConfig, pbufferAttribs)); + + size_t threadID{std::hash{}(std::this_thread::get_id())}; + _sharedContexts[threadID] = eglDefaultContext; + + makeCurrent(eglDefaultSurface, eglDefaultSurface, eglDefaultContext); + resetStates(); + + return true; +} + +void GLES3GPUContext::destroy() { + if (eglDisplay) { + makeCurrent(EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + } + + if (eglDefaultSurface) { + EGL_CHECK(eglDestroySurface(eglDisplay, eglDefaultSurface)); + eglDefaultSurface = EGL_NO_SURFACE; + } + + for (auto pair : _sharedContexts) { + if (pair.second != eglDefaultContext) { + EGL_CHECK(eglDestroyContext(eglDisplay, pair.second)); + } + } + _sharedContexts.clear(); + + if (eglDefaultContext) { + EGL_CHECK(eglDestroyContext(eglDisplay, eglDefaultContext)); + eglDefaultContext = EGL_NO_SURFACE; + } + + if (eglDisplay) { + EGL_CHECK(eglTerminate(eglDisplay)); + eglDisplay = EGL_NO_DISPLAY; + } +} + +void GLES3GPUContext::bindContext(bool bound) { + if (bound) { + makeCurrent(_eglCurrentDrawSurface, _eglCurrentReadSurface, eglDefaultContext); + resetStates(); + } else { + makeCurrent(EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT, false); + } +} + +void GLES3GPUContext::makeCurrent(const GLES3GPUSwapchain *drawSwapchain, const GLES3GPUSwapchain *readSwapchain) { + EGLSurface drawSurface = drawSwapchain ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; + EGLSurface readSurface = readSwapchain ? readSwapchain->eglSurface : _eglCurrentReadSurface; + if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface) return; + + makeCurrent(drawSurface, readSurface, _eglCurrentContext); +} + +void GLES3GPUContext::present(const GLES3GPUSwapchain *swapchain) { + if (_eglCurrentInterval != swapchain->eglSwapInterval) { + if (!eglSwapInterval(eglDisplay, swapchain->eglSwapInterval)) { + CC_LOG_ERROR("eglSwapInterval() - FAILED."); + } + _eglCurrentInterval = swapchain->eglSwapInterval; + } + EGL_CHECK(eglSwapBuffers(eglDisplay, swapchain->eglSurface)); +} + +EGLContext GLES3GPUContext::getSharedContext() { + size_t threadID{std::hash{}(std::this_thread::get_id())}; + if (_sharedContexts.count(threadID)) return _sharedContexts[threadID]; + + EGLContext context = EGL_NO_CONTEXT; + EGL_CHECK(context = eglCreateContext(eglDisplay, eglConfig, eglDefaultContext, eglAttributes.data())); + + if (!context) { + CC_LOG_ERROR("Create shared context failed."); + return EGL_NO_CONTEXT; + } + + _sharedContexts[threadID] = context; + return context; +} + +bool GLES3GPUContext::makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache) { + bool succeeded; + EGL_CHECK(succeeded = eglMakeCurrent(eglDisplay, drawSurface, readSurface, context)); + if (succeeded && updateCache) { + _eglCurrentDrawSurface = drawSurface; + _eglCurrentReadSurface = readSurface; + _eglCurrentContext = context; + } + return succeeded; +} + +void GLES3GPUContext::resetStates() const { + GL_CHECK(glPixelStorei(GL_PACK_ALIGNMENT, 1)); + GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); + GL_CHECK(glActiveTexture(GL_TEXTURE0)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glEnable(GL_SCISSOR_TEST)); + GL_CHECK(glEnable(GL_CULL_FACE)); + GL_CHECK(glCullFace(GL_BACK)); + + GL_CHECK(glFrontFace(GL_CCW)); + + GL_CHECK(glDisable(GL_SAMPLE_COVERAGE)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glEnable(GL_DEPTH_TEST)); + GL_CHECK(glDepthMask(GL_TRUE)); + GL_CHECK(glDepthFunc(GL_LESS)); + + GL_CHECK(glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xffffffff)); + GL_CHECK(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP)); + GL_CHECK(glStencilMaskSeparate(GL_FRONT, 0xffffffff)); + GL_CHECK(glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 1, 0xffffffff)); + GL_CHECK(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP)); + GL_CHECK(glStencilMaskSeparate(GL_BACK, 0xffffffff)); + + GL_CHECK(glDisable(GL_STENCIL_TEST)); + + ////////////////////////////////////////////////////////////////////////// + + GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE)); + GL_CHECK(glDisable(GL_BLEND)); + GL_CHECK(glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD)); + GL_CHECK(glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO)); + GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); + GL_CHECK(glBlendColor(0.0F, 0.0F, 0.0F, 0.0F)); + + GL_CHECK(glUseProgram(0)); + + GL_CHECK(glBindVertexArray(0)); + + GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_COPY_READ_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_COPY_WRITE_BUFFER, 0)); + + if (_constantRegistry->glMinorVersion) { + GL_CHECK(glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0)); + GL_CHECK(glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)); + } + + GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_3D, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0)); + + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)); + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION + GL_CHECK(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR)); + if (glDebugMessageControlKHR) { + GL_CHECK(glDebugMessageControlKHR(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE)); + } + if (glDebugMessageCallbackKHR) { + GL_CHECK(glDebugMessageCallbackKHR(GLES3EGLDebugProc, NULL)); + } +#endif + + if (_constantRegistry->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { + GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); + } + + _stateCache->reset(); + + _constantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); + + CC_LOG_DEBUG("EGL context bounded to thread %llx", _constantRegistry->currentBoundThreadID); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index f480d4c23d..1e60818427 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -25,8 +25,6 @@ #pragma once -#include - #include "gfx-base/GFXDef.h" #include "gfx-gles-common/GLESCommandPool.h" @@ -36,11 +34,10 @@ namespace cc { namespace gfx { -class GLES3GPUConstantRegistry { +class GLES3GPUConstantRegistry final : public Object { public: - uint currentBoundThreadID{0U}; - uint glMinorVersion{0U}; - uint defaultFramebuffer{0U}; + size_t currentBoundThreadID{0U}; + uint glMinorVersion{0U}; MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; FBFSupportLevel mFBF{FBFSupportLevel::NONE}; @@ -48,6 +45,58 @@ public: uint mPLSsize{0U}; }; +class GLES3GPUStateCache; +class GLES3GPUSwapchain; +class GLES3GPUContext final : public Object { +public: + bool initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstantRegistry *constantRegistry); + void destroy(); + + EGLint eglMajorVersion{0}; + EGLint eglMinorVersion{0}; + EGLDisplay eglDisplay{EGL_NO_DISPLAY}; + EGLConfig eglConfig{nullptr}; + vector eglAttributes; + + EGLSurface eglDefaultSurface{EGL_NO_SURFACE}; + EGLContext eglDefaultContext{EGL_NO_CONTEXT}; + + // pass nullptr to keep the current surface + void makeCurrent(const GLES3GPUSwapchain *drawSwapchain = nullptr, const GLES3GPUSwapchain *readSwapchain = nullptr); + void bindContext(bool bound); // for context switching between threads + + void present(const GLES3GPUSwapchain *swapchain); + + inline bool checkExtension(const String &extension) const { + return std::find(_extensions.begin(), _extensions.end(), extension) != _extensions.end(); + } + +private: + bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); + EGLContext getSharedContext(); + void resetStates() const; + + // state caches + EGLSurface _eglCurrentDrawSurface{EGL_NO_SURFACE}; + EGLSurface _eglCurrentReadSurface{EGL_NO_SURFACE}; + EGLContext _eglCurrentContext{EGL_NO_CONTEXT}; + EGLint _eglCurrentInterval{0}; + + GLES3GPUStateCache * _stateCache{nullptr}; + GLES3GPUConstantRegistry *_constantRegistry{nullptr}; + + map _sharedContexts; + + StringArray _extensions; +}; + +class GLES3GPUSwapchain final : public Object { +public: + EGLSurface eglSurface{EGL_NO_SURFACE}; + EGLint eglSwapInterval{0}; + GLuint glFramebuffer{0}; +}; + class GLES3GPUBuffer final : public Object { public: BufferUsage usage = BufferUsage::NONE; @@ -65,31 +114,32 @@ 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 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; + 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::ONE}; + 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}; + GLES3GPUSwapchain *swapchain{nullptr}; }; using GLES3GPUTextureList = vector; @@ -110,7 +160,8 @@ public: GLenum glWrapR = 0; }; -struct GLES3GPUInput final { +class GLES3GPUInput final : public Object { +public: uint binding = 0; String name; Type type = Type::UNKNOWN; @@ -122,7 +173,8 @@ struct GLES3GPUInput final { }; using GLES3GPUInputList = vector; -struct GLES3GPUUniform final { +class GLES3GPUUniform final : public Object { +public: uint binding = INVALID_BINDING; String name; Type type = Type::UNKNOWN; @@ -135,7 +187,8 @@ struct GLES3GPUUniform final { }; using GLES3GPUUniformList = vector; -struct GLES3GPUUniformBuffer final { +class GLES3GPUUniformBuffer final : public Object { +public: uint set = INVALID_BINDING; uint binding = INVALID_BINDING; String name; @@ -145,7 +198,8 @@ struct GLES3GPUUniformBuffer final { }; using GLES3GPUUniformBufferList = vector; -struct GLES3GPUUniformSamplerTexture final { +class GLES3GPUUniformSamplerTexture final : public Object { +public: uint set = 0; uint binding = 0; String name; @@ -158,7 +212,8 @@ struct GLES3GPUUniformSamplerTexture final { }; using GLES3GPUUniformSamplerTextureList = vector; -struct GLES3GPUUniformStorageImage final { +class GLES3GPUUniformStorageImage final : public Object { +public: uint set = 0; uint binding = 0; String name; @@ -171,7 +226,8 @@ struct GLES3GPUUniformStorageImage final { }; using GLES3GPUUniformStorageImageList = vector; -struct GLES3GPUShaderStage final { +class GLES3GPUShaderStage final : public Object { +public: GLES3GPUShaderStage(ShaderStageFlagBit t, String s, GLuint shader = 0) : type(t), source(std::move(std::move(s))), @@ -201,7 +257,8 @@ public: GLES3GPUUniformStorageImageList glImages; }; -struct GLES3GPUAttribute final { +class GLES3GPUAttribute final : public Object { +public: String name; GLuint glBuffer = 0; GLenum glType = 0; @@ -226,11 +283,18 @@ public: unordered_map glVAOs; }; +class GLES3GPUGlobalBarrier final : public Object { +public: + GLbitfield glBarriers = 0U; + GLbitfield glBarriersByRegion = 0U; +}; + class GLES3GPURenderPass final : public Object { public: - ColorAttachmentList colorAttachments; - DepthStencilAttachment depthStencilAttachment; - SubpassInfoList subpasses; + ColorAttachmentList colorAttachments; + DepthStencilAttachment depthStencilAttachment; + SubpassInfoList subpasses; + vector barriers; }; class GLES3GPUFramebuffer final : public Object { @@ -242,18 +306,31 @@ public: bool usesFBF = false; struct GLFramebuffer { - GLuint glFramebuffer = 0U; + inline void initialize(GLES3GPUSwapchain *sc) { swapchain = sc; } + inline void initialize(GLuint framebuffer) { _glFramebuffer = framebuffer; } + inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } + + void destroy(GLES3GPUStateCache *cache); + + GLES3GPUSwapchain *swapchain{nullptr}; + + private: + GLuint _glFramebuffer{0U}; + }; + + struct Framebuffer { + GLFramebuffer framebuffer; // for blit-based manual resolving - GLbitfield resolveMask = 0U; - GLuint glResolveFramebuffer = 0U; + GLbitfield resolveMask{0U}; + GLFramebuffer resolveFramebuffer; }; // one per subpass, if not using FBF or PLS - vector instances; + vector instances; - vector uberColorAttachmentIndices; - GLFramebuffer uberInstance; + vector uberColorAttachmentIndices; + Framebuffer uberInstance; }; class GLES3GPUDescriptorSetLayout final : public Object { @@ -291,7 +368,8 @@ public: GLES3GPUPipelineLayout *gpuPipelineLayout = nullptr; }; -struct GLES3GPUDescriptor final { +class GLES3GPUDescriptor final : public Object { +public: DescriptorType type = DescriptorType::UNKNOWN; GLES3GPUBuffer * gpuBuffer = nullptr; GLES3GPUTexture *gpuTexture = nullptr; @@ -305,13 +383,8 @@ public: const vector * descriptorIndices = nullptr; }; -class GLES3GPUGlobalBarrier final : public Object { +class GLES3GPUDispatchInfo final : public Object { public: - GLbitfield glBarriers = 0U; - GLbitfield glBarriersByRegion = 0U; -}; - -struct GLES3GPUDispatchInfo final : public Object { uint groupCountX = 0; uint groupCountY = 0; uint groupCountZ = 0; @@ -320,7 +393,8 @@ struct GLES3GPUDispatchInfo final : public Object { uint indirectOffset = 0; }; -struct GLES3ObjectCache final { +class GLES3ObjectCache final : public Object { +public: uint subpassIdx = 0U; GLES3GPURenderPass * gpuRenderPass = nullptr; GLES3GPUFramebuffer * gpuFramebuffer = nullptr; @@ -376,9 +450,12 @@ public: glImages.resize(imageUnits, 0U); glEnabledAttribLocs.resize(vertexAttributes, false); glCurrentAttribLocs.resize(vertexAttributes, false); + _initialized = true; } void reset() { + if (!_initialized) return; + glArrayBuffer = 0; glElementArrayBuffer = 0; glUniformBuffer = 0; @@ -416,6 +493,9 @@ public: gfxStateCache.glPrimitive = 0U; gfxStateCache.subpassIdx = 0U; } + +private: + bool _initialized{false}; }; class GLES3GPUFramebufferCacheMap final : public Object { @@ -430,6 +510,11 @@ public: auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; uint mipLevel = isTexture ? subres.mipLevel : 0; + if (gpuTexture->glTexture == 0 && gpuTexture->glRenderbuffer == 0) { + static const uint DEFAULT_FRAMEBUFFER = 0; + return DEFAULT_FRAMEBUFFER; + } + if (cacheMap[glResource].empty()) cacheMap[glResource].resize(gpuTexture->mipLevel, 0U); if (!cacheMap[glResource][mipLevel]) { @@ -490,49 +575,5 @@ private: CacheMap _textureMap; // texture -> mip level -> framebuffer }; -constexpr size_t CHUNK_SIZE = 16 * 1024 * 1024; // 16M per block by default -class GLES3GPUStagingBufferPool final : public Object { -public: - ~GLES3GPUStagingBufferPool() override { - for (Buffer &buffer : _pool) { - CC_FREE(buffer.mappedData); - } - _pool.clear(); - } - - uint8_t *alloc(size_t size) { - size_t bufferCount = _pool.size(); - Buffer *buffer = nullptr; - for (size_t idx = 0U; idx < bufferCount; idx++) { - Buffer *cur = &_pool[idx]; - if (CHUNK_SIZE - cur->curOffset >= size) { - buffer = cur; - break; - } - } - if (!buffer) { - _pool.resize(bufferCount + 1); - buffer = &_pool.back(); - buffer->mappedData = static_cast(CC_MALLOC(CHUNK_SIZE)); - } - uint8_t *data = buffer->mappedData + buffer->curOffset; - buffer->curOffset += size; - return data; - } - - void reset() { - for (Buffer &buffer : _pool) { - buffer.curOffset = 0U; - } - } - -private: - struct Buffer { - uint8_t *mappedData = nullptr; - size_t curOffset = 0U; - }; - vector _pool; -}; - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.cpp b/native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.cpp deleted file mode 100644 index de6774d493..0000000000 --- a/native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES3Std.h" - -#include "GLES3GPUObjects.h" -#include "GLES3GlobalBarrier.h" - -namespace cc { -namespace gfx { - -GLES3GlobalBarrier::GLES3GlobalBarrier() -: GlobalBarrier() { -} - -GLES3GlobalBarrier::~GLES3GlobalBarrier() { - CC_SAFE_DELETE(_gpuBarrier); -} - -void GLES3GlobalBarrier::doInit(const GlobalBarrierInfo &info) { - _gpuBarrier = CC_NEW(GLES3GPUGlobalBarrier); - - bool hasShaderWrites = false; - for (size_t i = 0u; i < info.prevAccesses.size(); ++i) { - switch (info.prevAccesses[i]) { - case AccessType::COMPUTE_SHADER_WRITE: - case AccessType::VERTEX_SHADER_WRITE: - case AccessType::FRAGMENT_SHADER_WRITE: - case AccessType::COLOR_ATTACHMENT_WRITE: - case AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE: - hasShaderWrites = true; - break; - default: - break; - } - } - - if (hasShaderWrites) { - for (size_t i = 0u; i < info.nextAccesses.size(); ++i) { - switch (info.nextAccesses[i]) { - case AccessType::INDIRECT_BUFFER: - _gpuBarrier->glBarriers |= GL_COMMAND_BARRIER_BIT; - break; - case AccessType::INDEX_BUFFER: - _gpuBarrier->glBarriers |= GL_ELEMENT_ARRAY_BARRIER_BIT; - break; - case AccessType::VERTEX_BUFFER: - _gpuBarrier->glBarriers |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; - break; - case AccessType::COMPUTE_SHADER_READ_UNIFORM_BUFFER: - case AccessType::VERTEX_SHADER_READ_UNIFORM_BUFFER: - case AccessType::FRAGMENT_SHADER_READ_UNIFORM_BUFFER: - _gpuBarrier->glBarriersByRegion |= GL_UNIFORM_BARRIER_BIT; - break; - case AccessType::COMPUTE_SHADER_READ_TEXTURE: - case AccessType::VERTEX_SHADER_READ_TEXTURE: - case AccessType::FRAGMENT_SHADER_READ_TEXTURE: - case AccessType::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT: - case AccessType::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT: - _gpuBarrier->glBarriersByRegion |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; - _gpuBarrier->glBarriersByRegion |= GL_TEXTURE_FETCH_BARRIER_BIT; - break; - case AccessType::COMPUTE_SHADER_READ_OTHER: - case AccessType::VERTEX_SHADER_READ_OTHER: - case AccessType::FRAGMENT_SHADER_READ_OTHER: - _gpuBarrier->glBarriersByRegion |= GL_SHADER_STORAGE_BARRIER_BIT; - break; - case AccessType::COLOR_ATTACHMENT_READ: - case AccessType::DEPTH_STENCIL_ATTACHMENT_READ: - _gpuBarrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; - break; - case AccessType::TRANSFER_READ: - _gpuBarrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_TEXTURE_UPDATE_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT; - break; - case AccessType::COMPUTE_SHADER_WRITE: - case AccessType::VERTEX_SHADER_WRITE: - case AccessType::FRAGMENT_SHADER_WRITE: - _gpuBarrier->glBarriersByRegion |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; - _gpuBarrier->glBarriersByRegion |= GL_SHADER_STORAGE_BARRIER_BIT; - break; - case AccessType::COLOR_ATTACHMENT_WRITE: - case AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE: - _gpuBarrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; - break; - case AccessType::TRANSFER_WRITE: - _gpuBarrier->glBarriersByRegion |= GL_FRAMEBUFFER_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_TEXTURE_UPDATE_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT; - _gpuBarrier->glBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT; - break; - case AccessType::HOST_PREINITIALIZED: - case AccessType::HOST_WRITE: - case AccessType::PRESENT: - default: - break; - } - } - } -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp index 5f1824e7f6..f02a8608e3 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp @@ -68,15 +68,5 @@ void GLES3InputAssembler::doDestroy() { } } -void GLES3InputAssembler::ExtractCmdDraw(GLES3CmdDraw *cmd) { - cmd->drawInfo.vertexCount = _vertexCount; - cmd->drawInfo.firstVertex = _firstVertex; - cmd->drawInfo.indexCount = _indexCount; - cmd->drawInfo.firstIndex = _firstIndex; - cmd->drawInfo.vertexOffset = _vertexOffset; - cmd->drawInfo.instanceCount = _instanceCount; - cmd->drawInfo.firstInstance = _firstInstance; -} - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.h b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.h index 56415f52e8..521395a0d5 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.h +++ b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXInputAssembler.h" namespace cc { @@ -36,9 +37,7 @@ class GLES3CmdDraw; class CC_GLES3_API GLES3InputAssembler final : public InputAssembler { public: GLES3InputAssembler(); - ~GLES3InputAssembler(); - - void ExtractCmdDraw(GLES3CmdDraw *cmd); + ~GLES3InputAssembler() override; inline GLES3GPUInputAssembler *gpuInputAssembler() const { return _gpuInputAssembler; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp index 16b8b47c6f..5a43346e2c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp @@ -28,6 +28,7 @@ #include "GLES3Commands.h" #include "GLES3DescriptorSetLayout.h" #include "GLES3PipelineLayout.h" +#include "base/Utils.h" namespace cc { namespace gfx { @@ -43,18 +44,18 @@ GLES3PipelineLayout::~GLES3PipelineLayout() { void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { _gpuPipelineLayout = CC_NEW(GLES3GPUPipelineLayout); - uint offset = 0U; + uint32_t offset = 0U; _gpuPipelineLayout->dynamicOffsetIndices.resize(_setLayouts.size()); - for (uint i = 0U; i < _setLayouts.size(); i++) { + for (uint32_t i = 0U; i < _setLayouts.size(); i++) { DescriptorSetLayout * setLayout = _setLayouts[i]; GLES3GPUDescriptorSetLayout *gpuSetLayout = static_cast(setLayout)->gpuDescriptorSetLayout(); - size_t dynamicCount = gpuSetLayout->dynamicBindings.size(); + uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); vector & indices = _gpuPipelineLayout->dynamicOffsetIndices[i]; indices.assign(setLayout->getBindingIndices().size(), -1); - for (uint j = 0U; j < dynamicCount; j++) { - uint binding = gpuSetLayout->dynamicBindings[j]; - if (indices[binding] < 0) indices[binding] = offset + j; + for (uint32_t j = 0U; j < dynamicCount; j++) { + uint32_t binding = gpuSetLayout->dynamicBindings[j]; + if (indices[binding] < 0) indices[binding] = static_cast(offset + j); } _gpuPipelineLayout->dynamicOffsetOffsets.push_back(offset); _gpuPipelineLayout->setLayouts.push_back(gpuSetLayout); diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.h b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.h index 3dcc59b3b2..84a591e3f7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.h @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXGLES3_PIPELINE_LAYOUT_H_ -#define CC_GFXGLES3_PIPELINE_LAYOUT_H_ +#pragma once +#include "GLES3Std.h" #include "gfx-base/GFXPipelineLayout.h" namespace cc { @@ -36,7 +36,7 @@ class GLES3GPUPipelineLayout; class CC_GLES3_API GLES3PipelineLayout final : public PipelineLayout { public: GLES3PipelineLayout(); - ~GLES3PipelineLayout(); + ~GLES3PipelineLayout() override; inline GLES3GPUPipelineLayout *gpuPipelineLayout() const { return _gpuPipelineLayout; } @@ -49,5 +49,3 @@ protected: } // namespace gfx } // namespace cc - -#endif // CC_GFXGLES3_PIPELINE_LAYOUT_H_ diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.h b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.h index 960894dcbd..d2ab126432 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXPipelineState.h" namespace cc { @@ -35,7 +36,7 @@ class GLES3GPUPipelineState; class CC_GLES3_API GLES3PipelineState final : public PipelineState { public: GLES3PipelineState(); - ~GLES3PipelineState(); + ~GLES3PipelineState() override; inline GLES3GPUPipelineState *gpuPipelineState() const { return _gpuPipelineState; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index 256e6e8c4e..1ef3e22429 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -26,15 +26,16 @@ #include "GLES3Std.h" #include "GLES3Buffer.h" +#include "GLES3Commands.h" #include "GLES3DescriptorSet.h" #include "GLES3Device.h" #include "GLES3Framebuffer.h" -#include "GLES3GlobalBarrier.h" #include "GLES3InputAssembler.h" #include "GLES3PipelineState.h" #include "GLES3PrimaryCommandBuffer.h" #include "GLES3RenderPass.h" #include "GLES3Texture.h" +#include "states/GLES3GlobalBarrier.h" namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Queue.h b/native/cocos/renderer/gfx-gles3/GLES3Queue.h index 030187e976..d4e0ae6967 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Queue.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Queue.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXQueue.h" namespace cc { @@ -33,7 +34,7 @@ namespace gfx { class CC_GLES3_API GLES3Queue final : public Queue { public: GLES3Queue(); - ~GLES3Queue(); + ~GLES3Queue() override; void submit(CommandBuffer *const *cmdBuffs, uint count) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 17a6828940..a83d93aced 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -27,6 +27,7 @@ #include "GLES3Commands.h" #include "GLES3RenderPass.h" +#include "base/Utils.h" namespace cc { namespace gfx { @@ -52,17 +53,16 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; } - subpass.depthStencil = _colorAttachments.size(); - } else { - // the depth stencil attachment is the default fallback - // when none are specified in subpass - const bool hasDepth = _depthStencilAttachment.format != Format::UNKNOWN; - for (auto &subpass : _gpuRenderPass->subpasses) { - if (hasDepth && subpass.depthStencil == INVALID_BINDING) { - subpass.depthStencil = static_cast(_colorAttachments.size()); - } + if (_depthStencilAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = _colorAttachments.size(); } } + + _gpuRenderPass->barriers.resize(_subpasses.size() + 1); + for (auto &dependency : _dependencies) { + size_t idx = dependency.dstSubpass == SUBPASS_EXTERNAL ? _subpasses.size() : dependency.dstSubpass; + cmdFuncGLES3CreateGlobalBarrier(dependency.srcAccesses, dependency.dstAccesses, &_gpuRenderPass->barriers[idx]); + } } void GLES3RenderPass::doDestroy() { diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.h b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.h index dfeca0a015..cf2f3717c7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.h +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXRenderPass.h" namespace cc { @@ -35,7 +36,7 @@ class GLES3GPURenderPass; class CC_GLES3_API GLES3RenderPass final : public RenderPass { public: GLES3RenderPass(); - ~GLES3RenderPass(); + ~GLES3RenderPass() override; inline GLES3GPURenderPass *gpuRenderPass() const { return _gpuRenderPass; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Shader.h b/native/cocos/renderer/gfx-gles3/GLES3Shader.h index 1cc11548b7..6d77db49ce 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Shader.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Shader.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXShader.h" namespace cc { @@ -35,7 +36,7 @@ class GLES3GPUShader; class CC_GLES3_API GLES3Shader final : public Shader { public: GLES3Shader(); - ~GLES3Shader(); + ~GLES3Shader() override; inline GLES3GPUShader *gpuShader() const { return _gpuShader; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp new file mode 100644 index 0000000000..44720e4b65 --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -0,0 +1,155 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GLES3Swapchain.h" +#include "GLES3Device.h" +#include "GLES3GPUObjects.h" +#include "GLES3Texture.h" + +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include "android/native_window.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include + #include +#endif + +namespace cc { +namespace gfx { + +GLES3Swapchain::GLES3Swapchain() { + _typedID = generateObjectID(); +} + +GLES3Swapchain::~GLES3Swapchain() { + destroy(); +} + +void GLES3Swapchain::doInit(const SwapchainInfo& info) { + const auto* context = GLES3Device::getInstance()->context(); + _gpuSwapchain = CC_NEW(GLES3GPUSwapchain); + auto* window = reinterpret_cast(info.windowHandle); + +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS + EGLint nFmt; + if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { + CC_LOG_ERROR("Getting configuration attributes failed."); + return; + } + + auto width = static_cast(info.width); + auto height = static_cast(info.height); + + #if CC_PLATFORM == CC_PLATFORM_ANDROID + ANativeWindow_setBuffersGeometry(window, width, height, nFmt); + #elif CC_PLATFORM == CC_PLATFORM_OHOS + NativeLayerHandle(window, NativeLayerOps::SET_WIDTH_AND_HEIGHT, width, height); + NativeLayerHandle(window, NativeLayerOps::SET_FORMAT, nFmt); + #endif +#endif + + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Create window surface failed."); + return; + } + + switch (_vsyncMode) { + case VsyncMode::OFF: _gpuSwapchain->eglSwapInterval = 0; break; + case VsyncMode::ON: + case VsyncMode::RELAXED: _gpuSwapchain->eglSwapInterval = 1; break; + case VsyncMode::MAILBOX: _gpuSwapchain->eglSwapInterval = 0; break; + case VsyncMode::HALF: _gpuSwapchain->eglSwapInterval = 2; break; + default: break; + } + + ///////////////////// Texture Creation ///////////////////// + + _colorTexture = CC_NEW(GLES3Texture); + _depthStencilTexture = CC_NEW(GLES3Texture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = Format::DEPTH_STENCIL; + initTexture(textureInfo, _depthStencilTexture); +} + +void GLES3Swapchain::doDestroy() { + if (!_gpuSwapchain) return; + + CC_SAFE_DESTROY(_depthStencilTexture) + CC_SAFE_DESTROY(_colorTexture) + + doDestroySurface(); + CC_SAFE_DELETE(_gpuSwapchain); +} + +void GLES3Swapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform /*transform*/) { + _colorTexture->resize(width, height); + _depthStencilTexture->resize(width, height); +} + +void GLES3Swapchain::doDestroySurface() { + if (_gpuSwapchain->eglSurface != EGL_NO_SURFACE) { + const auto* context = GLES3Device::getInstance()->context(); + eglDestroySurface(context->eglDisplay, _gpuSwapchain->eglSurface); + EGL_CHECK(eglMakeCurrent(context->eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); + _gpuSwapchain->eglSurface = EGL_NO_SURFACE; + } +} + +void GLES3Swapchain::doCreateSurface(void* windowHandle) { + auto* context = GLES3Device::getInstance()->context(); + auto* window = reinterpret_cast(windowHandle); + + EGLint nFmt = 0; + if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { + CC_LOG_ERROR("Getting configuration attributes failed."); + return; + } + +// Device's size will be updated after recreate window (in resize event) and is incorrect for now. +#if CC_PLATFORM == CC_PLATFORM_ANDROID + int32_t width = ANativeWindow_getWidth(window); + int32_t height = ANativeWindow_getHeight(window); + ANativeWindow_setBuffersGeometry(window, width, height, nFmt); +#elif CC_PLATFORM == CC_PLATFORM_OHOS + int32_t width = NativeLayerHandle(window, NativeLayerOps::GET_WIDTH); + int32_t height = NativeLayerHandle(window, NativeLayerOps::GET_HEIGHT); +#endif + + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Recreate window surface failed."); + return; + } +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.h b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.h new file mode 100644 index 0000000000..2c8ee22ef4 --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.h @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "GLES3Std.h" +#include "gfx-base/GFXSwapchain.h" + +namespace cc { +namespace gfx { + +class GLES3GPUSwapchain; + +class CC_GLES3_API GLES3Swapchain final : public Swapchain { +public: + GLES3Swapchain(); + ~GLES3Swapchain() override; + + inline GLES3GPUSwapchain *gpuSwapchain() const { return _gpuSwapchain; } + +protected: + void doInit(const SwapchainInfo &info) override; + void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; + + GLES3GPUSwapchain *_gpuSwapchain{nullptr}; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 8dc6007896..08766b9d75 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -27,6 +27,7 @@ #include "GLES3Commands.h" #include "GLES3Device.h" +#include "GLES3Swapchain.h" #include "GLES3Texture.h" namespace cc { @@ -42,18 +43,19 @@ GLES3Texture::~GLES3Texture() { void GLES3Texture::doInit(const TextureInfo& /*info*/) { _gpuTexture = CC_NEW(GLES3GPUTexture); - _gpuTexture->type = _type; - _gpuTexture->format = _format; - _gpuTexture->usage = _usage; - _gpuTexture->width = _width; - _gpuTexture->height = _height; - _gpuTexture->depth = _depth; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayer = _info.layerCount; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->arrayLayer = _layerCount; - _gpuTexture->mipLevel = _levelCount; - _gpuTexture->samples = _samples; - _gpuTexture->flags = _flags; - _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_width) && math::IsPowerOfTwo(_height); + _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); + _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES3CreateTexture(GLES3Device::getInstance(), _gpuTexture); @@ -92,5 +94,24 @@ void GLES3Texture::doResize(uint width, uint height, uint size) { } } +///////////////////////////// Swapchain Specific ///////////////////////////// + +void GLES3Texture::doInit(const SwapchainTextureInfo& /*info*/) { + _gpuTexture = CC_NEW(GLES3GPUTexture); + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayer = _info.layerCount; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; + _gpuTexture->memoryless = true; + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.h b/native/cocos/renderer/gfx-gles3/GLES3Texture.h index 1e3491679b..62dcc1c584 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.h @@ -25,6 +25,7 @@ #pragma once +#include "GLES3Std.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -35,7 +36,7 @@ class GLES3GPUTexture; class CC_GLES3_API GLES3Texture final : public Texture { public: GLES3Texture(); - ~GLES3Texture(); + ~GLES3Texture() override; inline GLES3GPUTexture *gpuTexture() const { return _gpuTexture; } @@ -44,6 +45,7 @@ protected: void doInit(const TextureViewInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; + void doInit(const SwapchainTextureInfo &info) override; GLES3GPUTexture *_gpuTexture = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.mm b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.mm deleted file mode 100644 index eefd790504..0000000000 --- a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.mm +++ /dev/null @@ -1,110 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "GLES3Wrangler.h" - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - #import - #import - #import - #import - #import - #import - -static CFBundleRef g_es3Bundle; -static CFURLRef g_es3BundleURL; - -static int gles3wOpen() { - #if TARGET_IPHONE_SIMULATOR - CFStringRef frameworkPath = CFSTR("/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks/OpenGLES.framework"); - #else - CFStringRef frameworkPath = CFSTR("/System/Library/Frameworks/OpenGLES.framework"); - #endif - - g_es3BundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, - frameworkPath, - kCFURLPOSIXPathStyle, true); - - CFRelease(frameworkPath); - - g_es3Bundle = CFBundleCreate(kCFAllocatorDefault, g_es3BundleURL); - - return (g_es3Bundle != NULL); -} - -static void *gles3wLoad(const char *proc) { - void *res; - - CFStringRef procname = CFStringCreateWithCString(kCFAllocatorDefault, proc, - kCFStringEncodingASCII); - res = CFBundleGetFunctionPointerForName(g_es3Bundle, procname); - CFRelease(procname); - return res; -} -#else - #include - #include - #include - #import - #import - -static void *libegl; -static void *libgl; - -static int gles3wOpen() { - NSURL *appURL = [[NSBundle mainBundle] bundleURL]; - - std::string libPath(appURL.resourceSpecifier.UTF8String); - libPath.append("/Contents/Frameworks/libEGL.dylib"); - libegl = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_LAZY); - if (!libegl) printf("%s\n", dlerror()); - - libPath = appURL.resourceSpecifier.UTF8String; - libPath.append("/Contents/Frameworks/libGLESv2.dylib"); - libgl = dlopen(libPath.c_str(), RTLD_LOCAL | RTLD_LAZY); - if (!libgl) printf("%s\n", dlerror()); - - return (libegl && libgl); -} - -static void *gles3wLoad(const char *proc) { - void *res = nullptr; - if (eglGetProcAddress) res = (void *)eglGetProcAddress(proc); - if (!res) res = (void *)dlsym(libegl, proc); - return res; -} -#endif - -bool gles3wInit() { - if (!gles3wOpen()) { - return false; - } - - eglwLoadProcs(gles3wLoad); - gles2wLoadProcs(gles3wLoad); - gles3wLoadProcs(gles3wLoad); - - return true; -} diff --git a/native/cocos/renderer/gfx-empty/EmptyContext.cpp b/native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.cpp similarity index 77% rename from native/cocos/renderer/gfx-empty/EmptyContext.cpp rename to native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.cpp index c558b54e98..7e3a2d34da 100644 --- a/native/cocos/renderer/gfx-empty/EmptyContext.cpp +++ b/native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.cpp @@ -23,22 +23,21 @@ THE SOFTWARE. ****************************************************************************/ -#include "EmptyContext.h" +#include "GLES3GlobalBarrier.h" +#include "../GLES3Commands.h" namespace cc { namespace gfx { -bool EmptyContext::doInit(const ContextInfo &info) { - _colorFmt = Format::RGBA8; - _depthStencilFmt = Format::D24S8; +GLES3GlobalBarrier::GLES3GlobalBarrier(const GlobalBarrierInfo &info) : GlobalBarrier(info) { + _typedID = generateObjectID(); - return true; + _gpuBarrier = CC_NEW(GLES3GPUGlobalBarrier); + cmdFuncGLES3CreateGlobalBarrier(info.prevAccesses, info.nextAccesses, _gpuBarrier); } -void EmptyContext::doDestroy() { -} - -void EmptyContext::present() { +GLES3GlobalBarrier::~GLES3GlobalBarrier() { + CC_SAFE_DELETE(_gpuBarrier); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.h b/native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.h similarity index 87% rename from native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.h rename to native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.h index 81b9132e3b..8541ed6030 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GlobalBarrier.h +++ b/native/cocos/renderer/gfx-gles3/states/GLES3GlobalBarrier.h @@ -24,23 +24,23 @@ ****************************************************************************/ #pragma once -#include "gfx-base/GFXGlobalBarrier.h" + +#include "../GLES3Std.h" +#include "gfx-base/states/GFXGlobalBarrier.h" namespace cc { namespace gfx { class GLES3GPUGlobalBarrier; -class CC_DLL GLES3GlobalBarrier : public GlobalBarrier { +class CC_GLES3_API GLES3GlobalBarrier : public GlobalBarrier { public: - GLES3GlobalBarrier(); - ~GLES3GlobalBarrier(); + explicit GLES3GlobalBarrier(const GlobalBarrierInfo &info); + ~GLES3GlobalBarrier() override; inline const GLES3GPUGlobalBarrier *gpuBarrier() const { return _gpuBarrier; } protected: - void doInit(const GlobalBarrierInfo &info) override; - GLES3GPUGlobalBarrier *_gpuBarrier = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Sampler.cpp b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp similarity index 80% rename from native/cocos/renderer/gfx-gles3/GLES3Sampler.cpp rename to native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp index ee98188f02..6636294ea8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Sampler.cpp +++ b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp @@ -23,36 +23,28 @@ THE SOFTWARE. ****************************************************************************/ -#include "GLES3Std.h" - -#include "GLES3Commands.h" -#include "GLES3Device.h" #include "GLES3Sampler.h" +#include "../GLES3Commands.h" +#include "../GLES3Device.h" namespace cc { namespace gfx { -GLES3Sampler::GLES3Sampler() { +GLES3Sampler::GLES3Sampler(const SamplerInfo &info) : Sampler(info) { _typedID = generateObjectID(); -} -GLES3Sampler::~GLES3Sampler() { - destroy(); -} - -void GLES3Sampler::doInit(const SamplerInfo& /*info*/) { _gpuSampler = CC_NEW(GLES3GPUSampler); - _gpuSampler->minFilter = _minFilter; - _gpuSampler->magFilter = _magFilter; - _gpuSampler->mipFilter = _mipFilter; - _gpuSampler->addressU = _addressU; - _gpuSampler->addressV = _addressV; - _gpuSampler->addressW = _addressW; + _gpuSampler->minFilter = _info.minFilter; + _gpuSampler->magFilter = _info.magFilter; + _gpuSampler->mipFilter = _info.mipFilter; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; cmdFuncGLES3CreateSampler(GLES3Device::getInstance(), _gpuSampler); } -void GLES3Sampler::doDestroy() { +GLES3Sampler::~GLES3Sampler() { if (_gpuSampler) { cmdFuncGLES3DestroySampler(GLES3Device::getInstance(), _gpuSampler); CC_DELETE(_gpuSampler); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Sampler.h b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.h similarity index 91% rename from native/cocos/renderer/gfx-gles3/GLES3Sampler.h rename to native/cocos/renderer/gfx-gles3/states/GLES3Sampler.h index a81502905f..497052d6c1 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Sampler.h +++ b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.h @@ -25,7 +25,8 @@ #pragma once -#include "gfx-base/GFXSampler.h" +#include "../GLES3Std.h" +#include "gfx-base/states/GFXSampler.h" namespace cc { namespace gfx { @@ -34,15 +35,12 @@ class GLES3GPUSampler; class CC_GLES3_API GLES3Sampler final : public Sampler { public: - GLES3Sampler(); - ~GLES3Sampler(); + explicit GLES3Sampler(const SamplerInfo &info); + ~GLES3Sampler() override; inline GLES3GPUSampler *gpuSampler() const { return _gpuSampler; } protected: - void doInit(const SamplerInfo &info) override; - void doDestroy() override; - GLES3GPUSampler *_gpuSampler = nullptr; }; diff --git a/native/cocos/renderer/gfx-metal/MTLBuffer.h b/native/cocos/renderer/gfx-metal/MTLBuffer.h index ac1159d420..a9b769e929 100644 --- a/native/cocos/renderer/gfx-metal/MTLBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLBuffer.h @@ -35,7 +35,7 @@ namespace cc { namespace gfx { class CCMTLCommandEncoder; -class CCMTLGPUBuffer; +struct CCMTLGPUBuffer; class CCMTLBuffer final : public Buffer { public: diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index ecc837bf56..44f1f9265e 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -41,6 +41,7 @@ class CCMTLInputAssembler; class CCMTLDevice; class CCMTLRenderPass; class CCMTLFence; +class CCMTLFramebuffer; class CCMTLCommandBuffer final : public CommandBuffer { public: @@ -76,8 +77,10 @@ public: void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint textureBarrierCount) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count); inline bool isCommandBufferBegan() const { return _commandBufferBegan; } - inline id getMTLCommandBuffer() const { return _mtlCommandBuffer; } - + inline CCMTLGPUCommandBufferObject* gpuCommandBufferObj() const { return _gpuCommandBufferObj; } + + void reset(); + protected: friend class CCMTLQueue; @@ -88,28 +91,20 @@ protected: void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor* descriptor); static bool isRenderingEntireDrawable(const Rect &rect, const CCMTLRenderPass *renderPass); - CCMTLGPUPipelineState *_gpuPipelineState = nullptr; - vector _GPUDescriptorSets; // NOLINT(bugprone-reserved-identifier) vector> _dynamicOffsets; uint _firstDirtyDescriptorSet = UINT_MAX; bool _indirectDrawSuppotred = false; bool _commandBufferBegan = false; - bool _isSecondary = false; CCMTLDevice *_mtlDevice = nullptr; id _mtlCommandQueue = nil; - id _mtlCommandBuffer = nil; CCMTLRenderCommandEncoder _renderEncoder; CCMTLComputeCommandEncoder _computeEncoder; id _parallelEncoder = nil; - CCMTLInputAssembler *_inputAssembler = nullptr; MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; - - //state cache - RenderPass *_curRenderPass = nullptr; - Framebuffer *_curFBO = nullptr; - + + CCMTLGPUCommandBufferObject* _gpuCommandBufferObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index d6634f26b4..ec9e703076 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -23,21 +23,23 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include -#include "MTLBuffer.h" -#include "MTLCommandBuffer.h" -#include "MTLDescriptorSet.h" -#include "MTLDevice.h" -#include "MTLFramebuffer.h" -#include "MTLInputAssembler.h" -#include "MTLPipelineState.h" -#include "MTLRenderPass.h" -#include "MTLSampler.h" -#include "MTLTexture.h" -#include "TargetConditionals.h" +#import +#import "MTLBuffer.h" +#import "MTLCommandBuffer.h" +#import "MTLDescriptorSet.h" +#import "MTLDevice.h" +#import "MTLFramebuffer.h" +#import "MTLInputAssembler.h" +#import "MTLPipelineState.h" +#import "MTLRenderPass.h" +#import "MTLSampler.h" +#import "MTLSwapchain.h" +#import "MTLTexture.h" +#import "TargetConditionals.h" #import +#import "MTLQueue.h" namespace cc { namespace gfx { @@ -59,25 +61,21 @@ CCMTLCommandBuffer::~CCMTLCommandBuffer() { } void CCMTLCommandBuffer::doInit(const CommandBufferInfo &info) { + _gpuCommandBufferObj = CC_NEW(CCMTLGPUCommandBufferObject); } void CCMTLCommandBuffer::doDestroy() { - _gpuPipelineState = nullptr; _GPUDescriptorSets.clear(); _dynamicOffsets.clear(); _firstDirtyDescriptorSet = UINT_MAX; _indirectDrawSuppotred = false; _commandBufferBegan = false; - _isSecondary = false; _mtlDevice = nullptr; _mtlCommandQueue = nil; - _mtlCommandBuffer = nil; _parallelEncoder = nil; - _inputAssembler = nullptr; - - //state cache - _curRenderPass = nullptr; - _curFBO = nullptr; + + // mtlCommandbuffer released in present.completeHandler + CC_SAFE_DELETE(_gpuCommandBufferObj); } bool CCMTLCommandBuffer::isRenderingEntireDrawable(const Rect &rect, const CCMTLRenderPass *renderPass) { @@ -94,11 +92,11 @@ void CCMTLCommandBuffer::begin(RenderPass *renderPass, uint subpass, Framebuffer return; } - _isSecondary = renderPass != nullptr && _mtlCommandBuffer; - if (!_isSecondary) { + if (!_gpuCommandBufferObj->isSecondary) { + auto* mtlQueue = static_cast(_queue)->gpuQueueObj()->mtlCommandQueue; // Only primary command buffer should request command buffer explicitly - _mtlCommandBuffer = [[_mtlCommandQueue commandBuffer] retain]; - [_mtlCommandBuffer enqueue]; + _gpuCommandBufferObj->mtlCommandBuffer = [mtlQueue commandBuffer]; + [_gpuCommandBufferObj->mtlCommandBuffer enqueue]; } _numTriangles = 0; @@ -120,7 +118,7 @@ void CCMTLCommandBuffer::end() { _commandBufferBegan = false; - if (_isSecondary) { + if (_gpuCommandBufferObj->isSecondary) { // Secondary command buffer should end encoding here _renderEncoder.endEncoding(); } @@ -128,33 +126,35 @@ void CCMTLCommandBuffer::end() { void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const *secondaryCBs, uint secondaryCBCount) { // Sub CommandBuffer shouldn't call begin render pass - if (_isSecondary) { + if (_gpuCommandBufferObj->isSecondary) { return; } - _curRenderPass = renderPass; - _curFBO = fbo; + _gpuCommandBufferObj->renderPass = static_cast(renderPass); + _gpuCommandBufferObj->fbo = static_cast(fbo); auto *ccMtlRenderPass = static_cast(renderPass); - auto isOffscreen = static_cast(fbo)->isOffscreen(); + auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen(); const SubpassInfoList& subpasses = renderPass->getSubpasses(); const ColorAttachmentList& colorAttachments = renderPass->getColorAttachments(); - + MTLRenderPassDescriptor *mtlRenderPassDescriptor = static_cast(renderPass)->getMTLRenderPassDescriptor(); const TextureList &colorTextures = fbo->getColorTextures(); Texture *dsTexture = fbo->getDepthStencilTexture(); - if (dsTexture) { - auto *ccMtlTexture = static_cast(dsTexture); - ccMtlRenderPass->setDepthStencilAttachment(static_cast(dsTexture), 0); - } else { - const DepthStencilAttachment& dsa = renderPass->getDepthStencilAttachment(); - if(dsa.format != Format::UNKNOWN) { - ccMtlRenderPass->setDepthStencilAttachment(nil, 0); - } - } + auto* swapchain = static_cast(_gpuCommandBufferObj->fbo->swapChain()); + if(subpasses.empty()) { - ccMtlRenderPass->setDepthStencilAttachment(nullptr, 0); + if (dsTexture) { + auto *ccMtlTexture = static_cast(dsTexture); + ccMtlRenderPass->setDepthStencilAttachment(ccMtlTexture, 0); + } else { + const DepthStencilAttachment& dsa = renderPass->getDepthStencilAttachment(); + if(dsa.format != Format::UNKNOWN) { + ccMtlRenderPass->setDepthStencilAttachment(swapchain->depthStencilTexture(), 0); + } + } + if(colorAttachments.empty()) { - ccMtlRenderPass->setColorAttachment(0, nullptr, 0); + ccMtlRenderPass->setColorAttachment(0, swapchain->colorTexture(), 0); }else { for (size_t i = 0; i < colorAttachments.size(); ++i) { auto *ccMtlTexture = static_cast(colorTextures[i]); @@ -195,7 +195,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb if(subpasses[i].resolves.size() > j) { uint32_t resolve = subpasses[i].resolves[j]; auto *resolveTex = static_cast(colorTextures[resolve]); - if(resolveTex->getSamples() == SampleCount::X1) + if(resolveTex->textureInfo().samples == SampleCount::ONE) continue; mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; @@ -211,25 +211,27 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb } updateDepthStencilState(ccMtlRenderPass->getCurrentSubpassIndex(), mtlRenderPassDescriptor); } - + mtlRenderPassDescriptor.depthAttachment.clearDepth = depth; mtlRenderPassDescriptor.stencilAttachment.clearStencil = stencil; + id mtlCommandBuffer = _gpuCommandBufferObj->mtlCommandBuffer; if (!isRenderingEntireDrawable(renderArea, static_cast(renderPass))) { //Metal doesn't apply the viewports and scissors to renderpass load-action clearing. - mu::clearRenderArea(_mtlDevice, _mtlCommandBuffer, renderPass, renderArea, colors, depth, stencil); + mu::clearRenderArea(_mtlDevice, mtlCommandBuffer, renderPass, renderArea, colors, depth, stencil); } if (secondaryCBCount > 0) { - _parallelEncoder = [[_mtlCommandBuffer parallelRenderCommandEncoderWithDescriptor:mtlRenderPassDescriptor] retain]; + _parallelEncoder = [[mtlCommandBuffer parallelRenderCommandEncoderWithDescriptor:mtlRenderPassDescriptor] retain]; // Create command encoders from parallel encoder and assign to command buffers for (uint i = 0u; i < secondaryCBCount; ++i) { CCMTLCommandBuffer *cmdBuff = (CCMTLCommandBuffer *)secondaryCBs[i]; cmdBuff->_renderEncoder.initialize(_parallelEncoder); - cmdBuff->_mtlCommandBuffer = _mtlCommandBuffer; + cmdBuff->_gpuCommandBufferObj->mtlCommandBuffer = mtlCommandBuffer; + cmdBuff->_gpuCommandBufferObj->isSecondary = true; } } else { - _renderEncoder.initialize(_mtlCommandBuffer, mtlRenderPassDescriptor); + _renderEncoder.initialize(mtlCommandBuffer, mtlRenderPassDescriptor); //[_renderEncoder.getMTLEncoder() memoryBarrierWithScope:MTLBarrierScopeTextures afterStages:MTLRenderStageFragment beforeStages:MTLRenderStageFragment]; } @@ -251,29 +253,39 @@ void CCMTLCommandBuffer::endRenderPass() { } else { _renderEncoder.endEncoding(); } - static_cast(_curRenderPass)->reset(); - _curRenderPass = nullptr; - _curFBO = nullptr; + _gpuCommandBufferObj->renderPass->reset(); +} + +void CCMTLCommandBuffer::reset() { + _gpuCommandBufferObj->renderPass = nullptr; + _gpuCommandBufferObj->fbo = nullptr; + _gpuCommandBufferObj->inputAssembler = nullptr; + _gpuCommandBufferObj->pipelineState = nullptr; + _gpuCommandBufferObj->mtlCommandBuffer = nil; } void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDescriptor *descriptor) { - const SubpassInfoList& subpasses = _curRenderPass->getSubpasses(); + CCMTLRenderPass* curRenderPass = _gpuCommandBufferObj->renderPass; + CCMTLFramebuffer* curFBO = _gpuCommandBufferObj->fbo; + const SubpassInfoList& subpasses = curRenderPass->getSubpasses(); const SubpassInfo subpass = subpasses[index]; if(subpass.depthStencil != INVALID_BINDING) { - const TextureList& colorTextures = _curFBO->getColorTextures(); + const TextureList& colorTextures = curFBO->getColorTextures(); if(subpass.depthStencil >= colorTextures.size() ) { - auto* ccMTLTexture = static_cast(_curFBO->getDepthStencilTexture()); + auto* ccMTLTexture = static_cast(curFBO->getDepthStencilTexture()); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); - descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); + if(ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) + descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); } else { auto* ccMTLTexture = static_cast(colorTextures[subpass.depthStencil]); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); - descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); + if(ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) + descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); } if(subpass.depthStencilResolve != INVALID_BINDING) { const CCMTLTexture* dsResolveTex = nullptr; if(subpass.depthStencilResolve >= colorTextures.size()) { - dsResolveTex = static_cast(_curFBO->getDepthStencilTexture()); + dsResolveTex = static_cast(curFBO->getDepthStencilTexture()); } else { dsResolveTex = static_cast(colorTextures[subpass.depthStencilResolve]); } @@ -282,13 +294,13 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - + descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); descriptor.stencilAttachment.resolveLevel = 0; descriptor.stencilAttachment.resolveSlice = 0; descriptor.stencilAttachment.resolveDepthPlane = 0; descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - + descriptor.depthAttachment.depthResolveFilter = mu::toMTLDepthResolveMode(subpass.depthResolveMode); descriptor.stencilAttachment.stencilResolveFilter = mu::toMTLStencilResolveMode(subpass.stencilResolveMode); } @@ -297,29 +309,33 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe void CCMTLCommandBuffer::bindPipelineState(PipelineState *pso) { PipelineBindPoint bindPoint = pso->getBindPoint(); + CCMTLGPUPipelineState* pplState = nullptr; + auto* ccPipeline = static_cast(pso); if (bindPoint == PipelineBindPoint::GRAPHICS) { - auto ccPipeline = static_cast(pso); - ccPipeline->check(); - _gpuPipelineState = ccPipeline->getGPUPipelineState(); - _mtlPrimitiveType = _gpuPipelineState->primitiveType; - _renderEncoder.setCullMode(_gpuPipelineState->cullMode); - _renderEncoder.setFrontFacingWinding(_gpuPipelineState->winding); - _renderEncoder.setDepthClipMode(_gpuPipelineState->depthClipMode); - _renderEncoder.setTriangleFillMode(_gpuPipelineState->fillMode); - _renderEncoder.setRenderPipelineState(_gpuPipelineState->mtlRenderPipelineState); + ccPipeline->check(_gpuCommandBufferObj->renderPass); + pplState = ccPipeline->getGPUPipelineState(); + _mtlPrimitiveType = pplState->primitiveType; - if (_gpuPipelineState->mtlDepthStencilState) { - _renderEncoder.setStencilFrontBackReferenceValue(_gpuPipelineState->stencilRefFront, _gpuPipelineState->stencilRefBack); - _renderEncoder.setDepthStencilState(_gpuPipelineState->mtlDepthStencilState); + _renderEncoder.setCullMode(pplState->cullMode); + _renderEncoder.setFrontFacingWinding(pplState->winding); + _renderEncoder.setDepthClipMode(pplState->depthClipMode); + _renderEncoder.setTriangleFillMode(pplState->fillMode); + _renderEncoder.setRenderPipelineState(pplState->mtlRenderPipelineState); + + if (pplState->mtlDepthStencilState) { + _renderEncoder.setStencilFrontBackReferenceValue(pplState->stencilRefFront, pplState->stencilRefBack); + _renderEncoder.setDepthStencilState(pplState->mtlDepthStencilState); } + } else if (bindPoint == PipelineBindPoint::COMPUTE) { if (!_computeEncoder.isInitialized()) { - _computeEncoder.initialize(_mtlCommandBuffer); + _computeEncoder.initialize(_gpuCommandBufferObj->mtlCommandBuffer); } - _gpuPipelineState = static_cast(pso)->getGPUPipelineState(); - _computeEncoder.setComputePipelineState(_gpuPipelineState->mtlComputePipelineState); + pplState = ccPipeline->getGPUPipelineState(); + _computeEncoder.setComputePipelineState(pplState->mtlComputePipelineState); } + _gpuCommandBufferObj->pipelineState = ccPipeline; } void CCMTLCommandBuffer::bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) { @@ -342,7 +358,7 @@ void CCMTLCommandBuffer::bindDescriptorSet(uint set, DescriptorSet *descriptorSe void CCMTLCommandBuffer::bindInputAssembler(InputAssembler *ia) { if (ia) { - _inputAssembler = static_cast(ia); + _gpuCommandBufferObj->inputAssembler = static_cast(ia); } } @@ -379,8 +395,9 @@ void CCMTLCommandBuffer::setStencilCompareMask(StencilFace /*face*/, uint /*ref* } void CCMTLCommandBuffer::nextSubpass() { - if(_curRenderPass) { - auto *ccRenderpass = static_cast(_curRenderPass); + CCMTLRenderPass* curRenderPass = _gpuCommandBufferObj->renderPass; + if(curRenderPass) { + auto *ccRenderpass = static_cast(curRenderPass); ccRenderpass->nextSubpass(); // with framebuffer fetch enabled we can get texture as attachments by color[n] (except mac before m1), @@ -390,16 +407,16 @@ void CCMTLCommandBuffer::nextSubpass() { _renderEncoder.endEncoding(); uint curSubpassIndex = ccRenderpass->getCurrentSubpassIndex(); auto *mtlRenderPassDescriptor = ccRenderpass->getMTLRenderPassDescriptor(); - const auto &colorAttachments = _curRenderPass->getColorAttachments(); + const auto &colorAttachments = curRenderPass->getColorAttachments(); const auto colorAttachmentCount = colorAttachments.size(); for (size_t slot = 0U; slot < colorAttachmentCount; slot++) { mtlRenderPassDescriptor.colorAttachments[slot].loadAction = MTLLoadActionLoad;// mu::toMTLLoadAction(colorAttachments[slot].loadOp); mtlRenderPassDescriptor.colorAttachments[slot].storeAction = mu::toMTLStoreAction(colorAttachments[slot].storeOp); } updateDepthStencilState(curSubpassIndex, mtlRenderPassDescriptor); - _renderEncoder.initialize(_mtlCommandBuffer, ccRenderpass->getMTLRenderPassDescriptor()); - const TextureList &colorTextures = _curFBO->getColorTextures(); - const SubpassInfoList& subpasses = _curRenderPass->getSubpasses(); + _renderEncoder.initialize(_gpuCommandBufferObj->mtlCommandBuffer, ccRenderpass->getMTLRenderPassDescriptor()); + const TextureList &colorTextures = _gpuCommandBufferObj->fbo->getColorTextures(); + const SubpassInfoList& subpasses = curRenderPass->getSubpasses(); if(!subpasses.empty()) { const auto& inputs = subpasses[curSubpassIndex].inputs; for (size_t i = 0; i < inputs.size(); i++) { @@ -416,9 +433,9 @@ void CCMTLCommandBuffer::draw(const DrawInfo &info) { if (_firstDirtyDescriptorSet < _GPUDescriptorSets.size()) { bindDescriptorSets(); } - - const auto *indirectBuffer = static_cast(_inputAssembler->getIndirectBuffer()); - const auto *indexBuffer = static_cast(_inputAssembler->getIndexBuffer()); + CCMTLInputAssembler* inputAssembler = _gpuCommandBufferObj->inputAssembler; + const auto *indirectBuffer = static_cast(inputAssembler->getIndirectBuffer()); + const auto *indexBuffer = static_cast(inputAssembler->getIndexBuffer()); auto mtlEncoder = _renderEncoder.getMTLEncoder(); if (indirectBuffer) { @@ -510,7 +527,7 @@ void CCMTLCommandBuffer::draw(const DrawInfo &info) { _numInstances += info.instanceCount; _numDrawCalls++; - if (_gpuPipelineState) { + if (_gpuCommandBufferObj->pipelineState) { uint indexCount = info.indexCount ? info.indexCount : info.vertexCount; switch (_mtlPrimitiveType) { case MTLPrimitiveTypeTriangle: @@ -535,7 +552,7 @@ void CCMTLCommandBuffer::updateBuffer(Buffer *buff, const void *data, uint size) stagingBuffer.size = size; _mtlDevice->gpuStagingBufferPool()->alloc(&stagingBuffer); memcpy(stagingBuffer.mappedData, data, size); - id encoder = [_mtlCommandBuffer blitCommandEncoder]; + id encoder = [_gpuCommandBufferObj->mtlCommandBuffer blitCommandEncoder]; [encoder copyFromBuffer:stagingBuffer.mtlBuffer sourceOffset:stagingBuffer.startOffset toBuffer:static_cast(buff)->getMTLBuffer() @@ -575,7 +592,7 @@ void CCMTLCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex } size_t offset = 0; - id encoder = [_mtlCommandBuffer blitCommandEncoder]; + id encoder = [_gpuCommandBufferObj->mtlCommandBuffer blitCommandEncoder]; id dstTexture = mtlTexture->getMTLTexture(); const bool isArrayTexture = mtlTexture->isArray(); for (size_t i = 0; i < count; i++) { @@ -597,7 +614,7 @@ void CCMTLCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex CC_FREE(convertedData); } } - if (hasFlag(texture->getFlags(), TextureFlags::GEN_MIPMAP) && mu::pixelFormatIsColorRenderable(convertedFormat)) { + if (hasFlag(static_cast(texture)->textureInfo().flags, TextureFlags::GEN_MIPMAP) && mu::pixelFormatIsColorRenderable(convertedFormat)) { [encoder generateMipmapsForTexture:dstTexture]; } [encoder endEncoding]; @@ -613,15 +630,17 @@ void CCMTLCommandBuffer::execute(CommandBuffer *const *commandBuffs, uint32_t co } void CCMTLCommandBuffer::bindDescriptorSets() { - const auto &vertexBuffers = _inputAssembler->getVertexBuffers(); - for (const auto &bindingInfo : _gpuPipelineState->vertexBufferBindingInfo) { + CCMTLInputAssembler* inputAssembler = _gpuCommandBufferObj->inputAssembler; + CCMTLGPUPipelineState* pipelineStateObj = _gpuCommandBufferObj->pipelineState->getGPUPipelineState(); + const auto &vertexBuffers = inputAssembler->getVertexBuffers(); + for (const auto &bindingInfo : pipelineStateObj->vertexBufferBindingInfo) { auto index = std::get<0>(bindingInfo); auto stream = std::get<1>(bindingInfo); static_cast(vertexBuffers[stream])->encodeBuffer(_renderEncoder, 0, index, ShaderStageFlagBit::VERTEX); } - const auto &dynamicOffsetIndices = _gpuPipelineState->gpuPipelineLayout->dynamicOffsetIndices; - const auto &blocks = _gpuPipelineState->gpuShader->blocks; + const auto &dynamicOffsetIndices = pipelineStateObj->gpuPipelineLayout->dynamicOffsetIndices; + const auto &blocks = pipelineStateObj->gpuShader->blocks; for (const auto &iter : blocks) { const auto &block = iter.second; @@ -638,7 +657,7 @@ void CCMTLCommandBuffer::bindDescriptorSets() { if (gpuDescriptor.buffer) { uint offset = (dynamicOffsetIndex >= 0) ? _dynamicOffsets[block.set][dynamicOffsetIndex] : 0; // compute pipeline and render pipeline mutually exlusive - if (_gpuPipelineState->mtlComputePipelineState) { + if (pipelineStateObj->mtlComputePipelineState) { gpuDescriptor.buffer->encodeBuffer(_computeEncoder, offset, block.mappedBinding, @@ -652,7 +671,7 @@ void CCMTLCommandBuffer::bindDescriptorSets() { } } - const auto &samplers = _gpuPipelineState->gpuShader->samplers; + const auto &samplers = pipelineStateObj->gpuShader->samplers; for (const auto &iter : samplers) { const auto &sampler = iter.second; @@ -682,21 +701,40 @@ void CCMTLCommandBuffer::bindDescriptorSets() { } void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) { - if (srcTexture && regions) { - id src = static_cast(srcTexture)->getMTLTexture(); - id dst = nil; - CCMTLDevice * device = CCMTLDevice::getInstance(); - if (!dstTexture) { - id currentDrawable = (id)device->getCurrentDrawable(); - dst = [currentDrawable texture]; + if (srcTexture && dstTexture && regions) { + + bool cmdActivated = _gpuCommandBufferObj->mtlCommandBuffer; + id mtlCmdBuffer = nil; + if(cmdActivated) { + mtlCmdBuffer = _gpuCommandBufferObj->mtlCommandBuffer; } else { - dst = static_cast(dstTexture)->getMTLTexture(); + mtlCmdBuffer = [static_cast(_queue)->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences]; + [mtlCmdBuffer enqueue]; } - + auto* ccSrcTex = static_cast(srcTexture); + auto* ccDstTex = static_cast(dstTexture); + + id src = nil; + if(ccSrcTex->swapChain()) { + src = ccSrcTex->swapChain()->currentDrawable().texture; + } else { + src = ccSrcTex->getMTLTexture(); + } + + id dst = nil; + if(ccDstTex->swapChain()) { + dst = ccDstTex->swapChain()->currentDrawable().texture; + } else { + dst = ccDstTex->getMTLTexture(); + } + id mtlDevice = static_cast>(_mtlDevice->getMTLDevice()); MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice: mtlDevice srcAlpha:MPSAlphaTypeNonPremultiplied destAlpha:MPSAlphaTypeNonPremultiplied backgroundColor:nil conversionInfo:nil]; - [conversion encodeToCommandBuffer:_mtlCommandBuffer sourceTexture:src destinationTexture:dst]; + [conversion encodeToCommandBuffer:mtlCmdBuffer sourceTexture:src destinationTexture:dst]; [conversion release]; + + if(!cmdActivated) + [mtlCmdBuffer commit]; } } @@ -721,7 +759,7 @@ void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buff auto *ccMTLTexture = static_cast(src); Format convertedFormat = ccMTLTexture->getConvertedFormat(); id mtlTexture = ccMTLTexture->getMTLTexture(); - + for (size_t i = 0; i < count; ++i) { uint32_t width = regions[i].texExtent.width; uint32_t height = regions[i].texExtent.height; @@ -730,7 +768,7 @@ void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buff uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); const Offset& origin = regions[i].texOffset; const Extent& extent = regions[i].texExtent; - + [mtlTexture getBytes:buffers[i] bytesPerRow:bytesPerRow bytesPerImage:bytesPerImage diff --git a/native/cocos/renderer/gfx-metal/MTLContext.mm b/native/cocos/renderer/gfx-metal/MTLContext.mm deleted file mode 100644 index 4772e5b0d0..0000000000 --- a/native/cocos/renderer/gfx-metal/MTLContext.mm +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "MTLStd.h" - -#include "MTLContext.h" -#include "MTLDevice.h" - -#import - -namespace cc { -namespace gfx { - -namespace { -Format toFormat(MTLPixelFormat format) { - switch (format) { - case MTLPixelFormatRGBA8Unorm: return Format::RGBA8; - case MTLPixelFormatBGRA8Unorm: return Format::BGRA8; -#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - case MTLPixelFormatDepth24Unorm_Stencil8: return Format::D24S8; -#endif - case MTLPixelFormatDepth32Float_Stencil8: return Format::D32F_S8; - default: - CC_LOG_ERROR("invalid MTLPixelFormat."); - return Format::UNKNOWN; - } -} -} - -CCMTLContext::CCMTLContext() -: Context() { -} - -bool CCMTLContext::doInit(const ContextInfo &info) { - _vsyncMode = info.vsyncMode; - _windowHandle = info.windowHandle; - - CCMTLDevice *device = CCMTLDevice::getInstance(); - CAMetalLayer *layer = (CAMetalLayer *)device->getMTLLayer(); - _colorFmt = toFormat(layer.pixelFormat); - id dsTex = (id)device->getDSTexture(); - _depthStencilFmt = toFormat(dsTex.pixelFormat); - - return true; -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index 5ca9464b99..11f06c8d14 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -25,14 +25,17 @@ #pragma once -#include "gfx-base/GFXDevice.h" -#include "MTLConfig.h" +#import "gfx-base/GFXDevice.h" +#import "MTLConfig.h" namespace cc { namespace gfx { +struct CCMTLGPUDeviceObject; + class CCMTLGPUStagingBufferPool; class CCMTLSemaphore; +class CCMTLSwapchain; class CCMTLDevice final : public Device { public: @@ -57,23 +60,15 @@ public: using Device::createPipelineState; using Device::createQueue; using Device::createRenderPass; - using Device::createSampler; using Device::createShader; using Device::createTexture; - using Device::createGlobalBarrier; - using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; void onPresentCompleted(); - void* getCurrentDrawable(); - void disposeCurrentDrawable(); - uint preferredPixelFormat(); inline void *getMTLCommandQueue() const { return _mtlCommandQueue; } - inline void *getMTLLayer() const { return _mtlLayer; } inline void *getMTLDevice() const { return _mtlDevice; } inline uint getMaximumSamplerUnits() const { return _maxSamplerUnits; } inline uint getMaximumColorRenderTargets() const { return _caps.maxColorRenderTargets; } @@ -83,7 +78,14 @@ public: inline CCMTLGPUStagingBufferPool *gpuStagingBufferPool() const { return _gpuStagingBufferPools[_currentFrameIndex]; } inline bool isSamplerDescriptorCompareFunctionSupported() const { return _isSamplerDescriptorCompareFunctionSupported; } inline uint currentFrameIndex() const { return _currentFrameIndex; } - inline void *getDSTexture() const { return _dsTex; } + + inline void registerSwapchain(CCMTLSwapchain* swapchain) { _swapchains.push_back(swapchain); } + inline void unRegisterSwapchain(CCMTLSwapchain* swapchain) { + auto iter = std::find(_swapchains.begin(), _swapchains.end(), swapchain); + if(iter != _swapchains.end()) { + _swapchains.erase(iter); + } + } protected: static CCMTLDevice * _instance; @@ -96,7 +98,6 @@ protected: Queue *createQueue() override; Buffer *createBuffer() override; Texture *createTexture() override; - Sampler *createSampler() override; Shader *createShader() override; InputAssembler *createInputAssembler() override; RenderPass *createRenderPass() override; @@ -105,8 +106,10 @@ protected: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout *createPipelineLayout() override; PipelineState *createPipelineState() override; - GlobalBarrier *createGlobalBarrier() override; - TextureBarrier *createTextureBarrier() override; + GlobalBarrier *createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo& info) override; + Sampler *createSampler(const SamplerInfo& info) override; + Swapchain *createSwapchain() override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; @@ -115,8 +118,6 @@ protected: void *_autoreleasePool = nullptr; void *_mtlCommandQueue = nullptr; void *_mtlDevice = nullptr; - void *_mtlLayer = nullptr; - void *_dsTex = nullptr; void *_activeDrawable = nullptr; unsigned long _mtlFeatureSet = 0; uint _maxSamplerUnits = 0; @@ -129,6 +130,10 @@ protected: uint _currentFrameIndex = 0; CCMTLSemaphore *_inFlightSemaphore = nullptr; CC_UNUSED uint32_t _memoryAlarmListenerId = 0; + + std::vector _swapchains; + + CCMTLGPUDeviceObject* _gpuDeviceObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index b05259859b..c5d9589785 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -23,27 +23,28 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLBuffer.h" -#include "MTLCommandBuffer.h" -#include "MTLConfig.h" -#include "MTLContext.h" -#include "MTLDescriptorSet.h" -#include "MTLDescriptorSetLayout.h" -#include "MTLDevice.h" -#include "MTLFramebuffer.h" -#include "MTLInputAssembler.h" -#include "MTLPipelineLayout.h" -#include "MTLPipelineState.h" -#include "MTLQueue.h" -#include "MTLRenderPass.h" -#include "MTLSampler.h" -#include "MTLSemaphore.h" -#include "MTLShader.h" -#include "MTLTexture.h" -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" +#import "MTLBuffer.h" +#import "MTLCommandBuffer.h" +#import "MTLConfig.h" +#import "MTLDescriptorSet.h" +#import "MTLDescriptorSetLayout.h" +#import "MTLDevice.h" +#import "MTLFramebuffer.h" +#import "MTLInputAssembler.h" +#import "MTLPipelineLayout.h" +#import "MTLPipelineState.h" +#import "MTLQueue.h" +#import "MTLRenderPass.h" +#import "MTLSampler.h" +#import "MTLSemaphore.h" +#import "MTLShader.h" +#import "MTLSwapchain.h" +#import "MTLTexture.h" +#import "cocos/bindings/event/CustomEventTypes.h" +#import "cocos/bindings/event/EventDispatcher.h" +#import "MTLGPUObjects.h" namespace cc { namespace gfx { @@ -70,25 +71,12 @@ CCMTLDevice::~CCMTLDevice() { } bool CCMTLDevice::doInit(const DeviceInfo &info) { + _gpuDeviceObj = CC_NEW(CCMTLGPUDeviceObject); _inFlightSemaphore = CC_NEW(CCMTLSemaphore(MAX_FRAMES_IN_FLIGHT)); _currentFrameIndex = 0; -#if CC_PLATFORM == CC_PLATFORM_MAC_OSX - NSView *view = (NSView *)_windowHandle; -#else - UIView *view = (UIView *)_windowHandle; -#endif - -#ifdef CC_USE_METAL - CAMetalLayer *layer = static_cast(view.layer); -#else - CAMetalLayer *layer = static_cast(view); -#endif - _mtlLayer = layer; - layer.framebufferOnly = NO; - id mtlDevice = (id)layer.device; + id mtlDevice = MTLCreateSystemDefaultDevice(); _mtlDevice = mtlDevice; - _mtlCommandQueue = [mtlDevice newCommandQueueWithMaxCommandBufferCount: MAX_COMMAND_BUFFER_COUNT]; _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); @@ -105,30 +93,6 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); - if (layer.pixelFormat == MTLPixelFormatInvalid) { - layer.pixelFormat = MTLPixelFormatBGRA8Unorm; - } - // Persistent depth stencil texture - MTLTextureDescriptor *dsDescriptor = [[MTLTextureDescriptor alloc] init]; - dsDescriptor.pixelFormat = mu::getSupportedDepthStencilFormat(mtlDevice, gpuFamily, _caps.depthBits); - dsDescriptor.width = info.width; - dsDescriptor.height = info.height; - dsDescriptor.storageMode = MTLStorageModePrivate; - dsDescriptor.usage = MTLTextureUsageRenderTarget; - _dsTex = [mtlDevice newTextureWithDescriptor:dsDescriptor]; - [dsDescriptor release]; - _caps.stencilBits = 8; - - - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - - _context = CC_NEW(CCMTLContext); - if (!_context->initialize(ctxInfo)) { - destroy(); - return false; - } - QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); @@ -191,6 +155,9 @@ void CCMTLDevice::doDestroy() { // EventDispatcher::removeCustomEventListener(EVENT_MEMORY_WARNING, _memoryAlarmListenerId); // _memoryAlarmListenerId = 0; // } + + CC_DELETE(_gpuDeviceObj); + if (_autoreleasePool) { [(NSAutoreleasePool*)_autoreleasePool drain]; _autoreleasePool = nullptr; @@ -202,14 +169,8 @@ void CCMTLDevice::doDestroy() { _inFlightSemaphore->syncAll(); } - if (_mtlCommandQueue) { - [id(_mtlCommandQueue) release]; - _mtlCommandQueue = nullptr; - } - CC_SAFE_DESTROY(_queue); CC_SAFE_DESTROY(_cmdBuff); - CC_SAFE_DESTROY(_context); CC_SAFE_DELETE(_inFlightSemaphore); for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { @@ -223,47 +184,50 @@ void CCMTLDevice::doDestroy() { CCASSERT(!_memoryStatus.textureSize, "Texture memory leaked"); } -void CCMTLDevice::resize(uint w, uint h) { - this->_width = w; - this->_height = h; - - [id(_dsTex) release]; - - MTLTextureDescriptor *dsDescriptor = [[MTLTextureDescriptor alloc] init]; - const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); - dsDescriptor.pixelFormat = mu::getSupportedDepthStencilFormat(id(this->_mtlDevice), gpuFamily, _caps.depthBits); - dsDescriptor.width = w; - dsDescriptor.height = h; - dsDescriptor.storageMode = MTLStorageModePrivate; - dsDescriptor.usage = MTLTextureUsageRenderTarget; - _dsTex = [id(this->_mtlDevice) newTextureWithDescriptor:dsDescriptor]; - [dsDescriptor release]; -} - -void CCMTLDevice::acquire() { +void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { _inFlightSemaphore->wait(); + for (CCMTLSwapchain* swapchain : _swapchains) { + swapchain->acquire(); + } + if (!_autoreleasePool) { _autoreleasePool = [[NSAutoreleasePool alloc] init]; // CC_LOG_INFO("POOL: %p ALLOCED", _autoreleasePool); } // Clear queue stats CCMTLQueue *queue = static_cast(_queue); - queue->_numDrawCalls = 0; - queue->_numInstances = 0; - queue->_numTriangles = 0; + queue->gpuQueueObj()->numDrawCalls = 0; + queue->gpuQueueObj()->numInstances = 0; + queue->gpuQueueObj()->numTriangles = 0; } void CCMTLDevice::present() { CCMTLQueue *queue = (CCMTLQueue *)_queue; - _numDrawCalls = queue->_numDrawCalls; - _numInstances = queue->_numInstances; - _numTriangles = queue->_numTriangles; + _numDrawCalls = queue->gpuQueueObj()->numDrawCalls; + _numInstances = queue->gpuQueueObj()->numInstances; + _numTriangles = queue->gpuQueueObj()->numTriangles; //hold this pointer before update _currentFrameIndex _currentBufferPoolId = _currentFrameIndex; _currentFrameIndex = (_currentFrameIndex + 1) % MAX_FRAMES_IN_FLIGHT; + id cmdBuffer = [queue->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences]; + + [cmdBuffer enqueue]; + + for (CCMTLSwapchain* swapchain: _swapchains) { + if (swapchain->currentDrawable()) { + [cmdBuffer presentDrawable:swapchain->currentDrawable()]; + swapchain->release(); + } + [cmdBuffer addCompletedHandler:^(id commandBuffer) { + onPresentCompleted(); + }]; + } + + [cmdBuffer commit]; + if (_autoreleasePool) { // CC_LOG_INFO("POOL: %p RELEASED", _autoreleasePool); [(NSAutoreleasePool*)_autoreleasePool drain]; @@ -282,18 +246,6 @@ void CCMTLDevice::onPresentCompleted() { _inFlightSemaphore->signal(); } -void *CCMTLDevice::getCurrentDrawable() { - if (!_activeDrawable) { - CAMetalLayer *layer = (CAMetalLayer*)getMTLLayer(); - _activeDrawable = [layer nextDrawable]; - } - return _activeDrawable; -} - -void CCMTLDevice::disposeCurrentDrawable() { - _activeDrawable = nil; -} - Queue *CCMTLDevice::createQueue() { return CC_NEW(CCMTLQueue); } @@ -310,10 +262,6 @@ Texture *CCMTLDevice::createTexture() { return CC_NEW(CCMTLTexture); } -Sampler *CCMTLDevice::createSampler() { - return CC_NEW(CCMTLSampler); -} - Shader *CCMTLDevice::createShader() { return CC_NEW(CCMTLShader); } @@ -346,12 +294,20 @@ PipelineState *CCMTLDevice::createPipelineState() { return CC_NEW(CCMTLPipelineState); } -GlobalBarrier *CCMTLDevice::createGlobalBarrier() { - return CC_NEW(GlobalBarrier); +GlobalBarrier *CCMTLDevice::createGlobalBarrier(const GlobalBarrierInfo& info) { + return new GlobalBarrier(info); } -TextureBarrier *CCMTLDevice::createTextureBarrier() { - return CC_NEW(TextureBarrier); +TextureBarrier *CCMTLDevice::createTextureBarrier(const TextureBarrierInfo& info) { + return new TextureBarrier(info); +} + +Sampler *CCMTLDevice::createSampler(const SamplerInfo &info) { + return new CCMTLSampler(info); +} + +Swapchain *CCMTLDevice::createSwapchain() { + return new CCMTLSwapchain(); } void CCMTLDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint count) { @@ -375,9 +331,5 @@ void CCMTLDevice::onMemoryWarning() { } } -uint CCMTLDevice::preferredPixelFormat() { - return static_cast([((CAMetalLayer*)_mtlLayer) pixelFormat]); -} - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLFramebuffer.h b/native/cocos/renderer/gfx-metal/MTLFramebuffer.h index 6d6e4c5cb2..769bd9c473 100644 --- a/native/cocos/renderer/gfx-metal/MTLFramebuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLFramebuffer.h @@ -25,11 +25,11 @@ #pragma once -#include "gfx-base/GFXFramebuffer.h" +#import "gfx-base/GFXFramebuffer.h" namespace cc { namespace gfx { - +class CCMTLSwapchain; class CCMTLFramebuffer final : public Framebuffer { public: explicit CCMTLFramebuffer(); @@ -40,12 +40,14 @@ public: CCMTLFramebuffer &operator=(CCMTLFramebuffer &&)=delete; inline bool isOffscreen() const { return _isOffscreen; } + inline CCMTLSwapchain* swapChain() const { return _swapChain; } protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; bool _isOffscreen = false; + CCMTLSwapchain* _swapChain = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm index b8174157b7..52c1007b06 100644 --- a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLFramebuffer.h" -#include "MTLRenderPass.h" -#include "MTLTexture.h" +#import "MTLFramebuffer.h" +#import "MTLRenderPass.h" +#import "MTLTexture.h" namespace cc { namespace gfx { @@ -40,11 +40,28 @@ CCMTLFramebuffer::~CCMTLFramebuffer() { destroy(); } -void CCMTLFramebuffer::doInit(const FramebufferInfo &info) { - _isOffscreen = (_colorTextures.size() != 0); +void CCMTLFramebuffer::doInit(const FramebufferInfo &) { + _isOffscreen = true; + for (Texture* tex : _colorTextures) { + auto* ccTex = static_cast(tex); + if(ccTex->swapChain()) { + _swapChain = ccTex->swapChain(); + _isOffscreen = false; + break; + } + } + + if(_depthStencilTexture) { + auto* ccTex = static_cast(_depthStencilTexture); + if(ccTex->swapChain()) { + _swapChain = ccTex->swapChain(); + _isOffscreen = false; + } + } } void CCMTLFramebuffer::doDestroy() { + _swapChain = nullptr; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index f0ce2eb359..ccdd1f2634 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -25,7 +25,7 @@ #pragma once -#include +#import #import "MTLConfig.h" #import "MTLUtils.h" @@ -33,6 +33,8 @@ #import #import #import "../../base/Utils.h" +#import +#import namespace cc { namespace gfx { @@ -40,6 +42,11 @@ class CCMTLBuffer; class CCMTLTexture; class CCMTLSampler; class CCMTLShader; +class CCMTLQueue; +class CCMTLRenderPass; +class CCMTLFramebuffer; +class CCMTLInputAssembler; +class CCMTLPipelineState; namespace { constexpr size_t MegaBytesToBytes = 1024 * 1024; @@ -122,6 +129,16 @@ struct CCMTLGPUBuffer { id mtlBuffer = nil; }; +struct CCMTLGPUTextureObject { + TextureInfo info; + id mtlTexture; +}; + +struct CCMTLGPUTextureViewObject { + TextureViewInfo viewInfo; + id mtlTextureView; +}; + class CCMTLGPUInputAssembler : public Object { public: id mtlIndexBuffer = nil; @@ -308,5 +325,30 @@ protected: std::queue _releaseQueue[MAX_FRAMES_IN_FLIGHT]; }; +struct CCMTLGPUSwapChainObject { + id currentDrawable = nil; + CAMetalLayer* mtlLayer = nullptr; +}; + +struct CCMTLGPUQueueObject { + id mtlCommandQueue = nil; + uint numDrawCalls = 0; + uint numInstances = 0; + uint numTriangles = 0; +}; + +struct CCMTLGPUCommandBufferObject { + CCMTLRenderPass *renderPass = nullptr; + CCMTLFramebuffer *fbo = nullptr; + CCMTLInputAssembler *inputAssembler = nullptr; + CCMTLPipelineState *pipelineState = nullptr; + id mtlCommandBuffer = nil; + bool isSecondary = false; +}; + +struct CCMTLGPUDeviceObject { + +}; + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.h b/native/cocos/renderer/gfx-metal/MTLPipelineState.h index 28e4a4280d..244f9e103e 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.h +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.h @@ -35,6 +35,8 @@ namespace cc { namespace gfx { +class CCMTLRenderPass; + class CCMTLPipelineState final : public PipelineState { public: explicit CCMTLPipelineState(); @@ -46,7 +48,7 @@ public: inline CCMTLGPUPipelineState *getGPUPipelineState() const { return _GPUPipelineState; } - void check(); + void check(CCMTLRenderPass* renderPass = nullptr); protected: void doInit(const PipelineStateInfo &info) override; diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 843f495239..5c2766c4e1 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -23,17 +23,17 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLDevice.h" -#include "MTLGPUObjects.h" -#include "MTLPipelineLayout.h" -#include "MTLPipelineState.h" -#include "MTLSampler.h" -#include "MTLShader.h" -#include "MTLTexture.h" -#include "MTLUtils.h" -#include "MTLRenderPass.h" +#import "MTLDevice.h" +#import "MTLGPUObjects.h" +#import "MTLPipelineLayout.h" +#import "MTLPipelineState.h" +#import "MTLSampler.h" +#import "MTLShader.h" +#import "MTLTexture.h" +#import "MTLUtils.h" +#import "MTLRenderPass.h" #import #import @@ -99,7 +99,9 @@ bool CCMTLPipelineState::initRenderPipeline() { return true; } -void CCMTLPipelineState::check() { +void CCMTLPipelineState::check(CCMTLRenderPass* renderPass) { + if(renderPass) + _renderPass = renderPass; if(!_renderPipelineReady) { initRenderPipeline(); } @@ -308,9 +310,9 @@ void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * } } - SampleCount sample = SampleCount::X1; + SampleCount sample = SampleCount::ONE; Format depthStencilFormat; - if(depthStencilTexIndex != INVALID_BINDING) { + if(depthStencilTexIndex != INVALID_BINDING && depthStencilTexIndex < _renderPass->getColorAttachments().size()) { sample = _renderPass->getColorAttachments()[depthStencilTexIndex].sampleCount; depthStencilFormat = _renderPass->getColorAttachments()[depthStencilTexIndex].format; } else { @@ -325,8 +327,11 @@ void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * mtlPixelFormat = mu::toMTLPixelFormat(depthStencilFormat); if (mtlPixelFormat != MTLPixelFormatInvalid) { - descriptor.stencilAttachmentPixelFormat = mtlPixelFormat; + descriptor.depthAttachmentPixelFormat = mtlPixelFormat; + + if(depthStencilFormat == Format::DEPTH_STENCIL) + descriptor.stencilAttachmentPixelFormat = mtlPixelFormat; } } diff --git a/native/cocos/renderer/gfx-metal/MTLQueue.h b/native/cocos/renderer/gfx-metal/MTLQueue.h index 0a6541b688..8b71d3e3b7 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueue.h +++ b/native/cocos/renderer/gfx-metal/MTLQueue.h @@ -25,11 +25,11 @@ #pragma once -#include "gfx-base/GFXQueue.h" +#import "gfx-base/GFXQueue.h" namespace cc { namespace gfx { - +struct CCMTLGPUQueueObject; class CCMTLQueue final : public Queue { friend class CCMTLDevice; @@ -42,14 +42,14 @@ public: CCMTLQueue &operator=(CCMTLQueue &&)=delete; void submit(CommandBuffer *const *cmdBuffs, uint count) override; + + inline CCMTLGPUQueueObject* gpuQueueObj() { return _gpuQueueObj; } protected: void doInit(const QueueInfo &info) override; void doDestroy() override; - - uint _numDrawCalls = 0; - uint _numInstances = 0; - uint _numTriangles = 0; + + CCMTLGPUQueueObject* _gpuQueueObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLQueue.mm b/native/cocos/renderer/gfx-metal/MTLQueue.mm index 9115740fe0..58afd2980a 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueue.mm +++ b/native/cocos/renderer/gfx-metal/MTLQueue.mm @@ -23,12 +23,14 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" - -#include "MTLQueue.h" -#include "MTLDevice.h" -#include "MTLCommandBuffer.h" +#import "MTLStd.h" +#import "MTLQueue.h" +#import "MTLDevice.h" +#import "MTLCommandBuffer.h" +#import "MTLGPUObjects.h" +#import "MTLFramebuffer.h" +#import "MTLSwapchain.h" namespace cc { namespace gfx { @@ -42,36 +44,36 @@ CCMTLQueue::~CCMTLQueue() { } void CCMTLQueue::doInit(const QueueInfo &info) { + _gpuQueueObj = CC_NEW(CCMTLGPUQueueObject); + auto device = static_cast>(CCMTLDevice::getInstance()->getMTLDevice()); + _gpuQueueObj->mtlCommandQueue = [device newCommandQueue]; } void CCMTLQueue::doDestroy() { + if(_gpuQueueObj) { + id mtlCmdQueue = _gpuQueueObj->mtlCommandQueue; + _gpuQueueObj->mtlCommandQueue = nil; + + auto destroyFunc = [mtlCmdQueue]() { + if(mtlCmdQueue) { + [mtlCmdQueue release]; + } + }; + CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc); + + CC_SAFE_DELETE(_gpuQueueObj); + } } void CCMTLQueue::submit(CommandBuffer *const *cmdBuffs, uint count) { for (uint i = 0u; i < count; ++i) { - CCMTLCommandBuffer *cmdBuffer = (CCMTLCommandBuffer *)cmdBuffs[i]; - _numDrawCalls += cmdBuffer->getNumDrawCalls(); - _numInstances += cmdBuffer->getNumInstances(); - _numTriangles += cmdBuffer->getNumTris(); - id mtlCmdBuffer = cmdBuffer->getMTLCommandBuffer(); - - if (i < count-1) { - [mtlCmdBuffer addCompletedHandler:^(id commandBuffer) { - [commandBuffer release]; - }]; - } - else { - // Must do present before commit last command buffer. - CCMTLDevice* device = (CCMTLDevice*)CCMTLDevice::getInstance(); - id currDrawable = (id)device->getCurrentDrawable(); - [mtlCmdBuffer presentDrawable:currDrawable]; - [mtlCmdBuffer addCompletedHandler:^(id commandBuffer) { - [commandBuffer release]; - device->onPresentCompleted(); - }]; - device->disposeCurrentDrawable(); - } + CCMTLCommandBuffer *cmdBuffer = static_cast(cmdBuffs[i]); + _gpuQueueObj->numDrawCalls += cmdBuffer->getNumDrawCalls(); + _gpuQueueObj->numInstances += cmdBuffer->getNumInstances(); + _gpuQueueObj->numTriangles += cmdBuffer->getNumTris(); + id mtlCmdBuffer = cmdBuffer->gpuCommandBufferObj()->mtlCommandBuffer; [mtlCmdBuffer commit]; + cmdBuffer->reset(); } } diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm index 36bc5bf431..bcb58d941c 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm @@ -77,12 +77,7 @@ void CCMTLRenderPass::setColorAttachment(size_t slot, CCMTLTexture* cctex, int l return; } - id texture = nil; - if(!cctex) { - texture = [static_cast>(CCMTLDevice::getInstance()->getCurrentDrawable()) texture]; - } else { - texture = cctex->getMTLTexture(); - } + id texture = cctex->getMTLTexture(); _mtlRenderPassDescriptor.colorAttachments[slot].texture = texture; _mtlRenderPassDescriptor.colorAttachments[slot].level = level; @@ -95,17 +90,14 @@ void CCMTLRenderPass::setDepthStencilAttachment(CCMTLTexture* cctex, int level) return; } - id texture = nil; - if(!cctex) { - texture = static_cast>(CCMTLDevice::getInstance()->getDSTexture()); - } else { - texture = cctex->getMTLTexture(); - } + id texture = cctex->getMTLTexture(); _mtlRenderPassDescriptor.depthAttachment.texture = texture; _mtlRenderPassDescriptor.depthAttachment.level = level; - _mtlRenderPassDescriptor.stencilAttachment.texture = texture; - _mtlRenderPassDescriptor.stencilAttachment.level = level; + if(cctex->getFormat() == Format::DEPTH_STENCIL) { + _mtlRenderPassDescriptor.stencilAttachment.texture = texture; + _mtlRenderPassDescriptor.stencilAttachment.level = level; + } } } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLSampler.h b/native/cocos/renderer/gfx-metal/MTLSampler.h index e7c6ea7fc4..01be302526 100644 --- a/native/cocos/renderer/gfx-metal/MTLSampler.h +++ b/native/cocos/renderer/gfx-metal/MTLSampler.h @@ -25,7 +25,7 @@ #pragma once -#include "gfx-base/GFXSampler.h" +#import "gfx-base/states/GFXSampler.h" #import @@ -34,8 +34,9 @@ namespace gfx { class CCMTLSampler final : public Sampler { public: - explicit CCMTLSampler(); + explicit CCMTLSampler(const SamplerInfo& info); ~CCMTLSampler(); + CCMTLSampler() = delete; CCMTLSampler(const CCMTLSampler &)=delete; CCMTLSampler(CCMTLSampler &&)=delete; CCMTLSampler &operator=(const CCMTLSampler &)=delete; @@ -44,8 +45,6 @@ public: inline id getMTLSamplerState() const { return _mtlSamplerState; } protected: - void doInit(const SamplerInfo &info) override; - void doDestroy() override; id _mtlSamplerState = nil; }; diff --git a/native/cocos/renderer/gfx-metal/MTLSampler.mm b/native/cocos/renderer/gfx-metal/MTLSampler.mm index 8f3d660174..d5ef6ce131 100644 --- a/native/cocos/renderer/gfx-metal/MTLSampler.mm +++ b/native/cocos/renderer/gfx-metal/MTLSampler.mm @@ -23,39 +23,32 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLDevice.h" -#include "MTLGPUObjects.h" -#include "MTLSampler.h" -#include "MTLUtils.h" +#import "MTLDevice.h" +#import "MTLGPUObjects.h" +#import "MTLSampler.h" +#import "MTLUtils.h" #import namespace cc { namespace gfx { -CCMTLSampler::CCMTLSampler() : Sampler() { +CCMTLSampler::CCMTLSampler(const SamplerInfo& info) : Sampler(info) { _typedID = generateObjectID(); -} - -CCMTLSampler::~CCMTLSampler() { - destroy(); -} - -void CCMTLSampler::doInit(const SamplerInfo &info) { MTLSamplerDescriptor *descriptor = [[MTLSamplerDescriptor alloc] init]; #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - descriptor.borderColor = (MTLSamplerBorderColor)mu::toMTLSamplerBorderColor(_borderColor); + descriptor.borderColor = MTLSamplerBorderColorTransparentBlack; #endif - descriptor.sAddressMode = mu::toMTLSamplerAddressMode(_addressU); - descriptor.tAddressMode = mu::toMTLSamplerAddressMode(_addressV); - descriptor.rAddressMode = mu::toMTLSamplerAddressMode(_addressW); - descriptor.minFilter = mu::toMTLSamplerMinMagFilter(_minFilter); - descriptor.magFilter = mu::toMTLSamplerMinMagFilter(_magFilter); - descriptor.mipFilter = mu::toMTLSamplerMipFilter(_mipFilter); - descriptor.maxAnisotropy = _maxAnisotropy == 0 ? 1 : _maxAnisotropy; + descriptor.sAddressMode = mu::toMTLSamplerAddressMode(info.addressU); + descriptor.tAddressMode = mu::toMTLSamplerAddressMode(info.addressV); + descriptor.rAddressMode = mu::toMTLSamplerAddressMode(info.addressW); + descriptor.minFilter = mu::toMTLSamplerMinMagFilter(info.minFilter); + descriptor.magFilter = mu::toMTLSamplerMinMagFilter(info.magFilter); + descriptor.mipFilter = mu::toMTLSamplerMipFilter(info.mipFilter); + descriptor.maxAnisotropy = info.maxAnisotropy == 0 ? 1 : info.maxAnisotropy; if (CCMTLDevice::getInstance()->isSamplerDescriptorCompareFunctionSupported()) { - descriptor.compareFunction = mu::toMTLCompareFunction(_cmpFunc); + descriptor.compareFunction = mu::toMTLCompareFunction(info.cmpFunc); } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); @@ -64,11 +57,11 @@ void CCMTLSampler::doInit(const SamplerInfo &info) { [descriptor release]; } -void CCMTLSampler::doDestroy() { +CCMTLSampler::~CCMTLSampler() { id samplerState = _mtlSamplerState; _mtlSamplerState = nil; - std::function destroyFunc = [=]() { + std::function destroyFunc = [samplerState]() { if (samplerState) { [samplerState release]; } diff --git a/native/cocos/renderer/gfx-metal/MTLShader.h b/native/cocos/renderer/gfx-metal/MTLShader.h index c324ed3799..832bd330b5 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.h +++ b/native/cocos/renderer/gfx-metal/MTLShader.h @@ -32,6 +32,7 @@ namespace cc { namespace gfx { class CCMTLGPUShader; +class SPIRVUtils; class CCMTLShader final : public Shader { public: explicit CCMTLShader(); @@ -83,6 +84,8 @@ protected: vector _availableFragmentBufferBindingIndex; CCMTLGPUShader *_gpuShader = nullptr; + + static SPIRVUtils* spirv; // For debug #ifdef DEBUG_SHADER diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 1736fdeba7..676ff110b7 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -23,16 +23,19 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLDevice.h" -#include "MTLGPUObjects.h" -#include "MTLShader.h" +#import "MTLDevice.h" +#import "MTLGPUObjects.h" +#import "MTLShader.h" #import +#import "gfx-base/SPIRVUtils.h" namespace cc { namespace gfx { +SPIRVUtils* CCMTLShader::spirv = nullptr; + CCMTLShader::CCMTLShader() : Shader() { _typedID = generateObjectID(); } @@ -123,16 +126,22 @@ bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - - auto mtlShader = mu::compileGLSLShader2Msl(stage.source, - stage.stage, - CCMTLDevice::getInstance(), - _gpuShader); + if(!spirv) { + spirv = SPIRVUtils::getInstance(); + spirv->initialize(2); // vulkan >= 1.2 spirv >= 1.5 + } + + spirv->compileGLSL(stage.stage, "#version 450\n" + stage.source); + if (stage.stage == ShaderStageFlagBit::VERTEX) spirv->compressInputLocations(_attributes); + + auto* spvData = spirv->getOutputData(); + size_t unitSize = sizeof(std::remove_pointer::type); + String mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize()/unitSize, stage.stage, _gpuShader); NSString * rawSrc = [NSString stringWithUTF8String:stage.source.c_str()]; - NSString * shader = [NSString stringWithUTF8String:mtlShader.c_str()]; + NSString * shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; NSError * error = nil; - MTLCompileOptions *opts = [[MTLCompileOptions alloc] init];; + MTLCompileOptions *opts = [[MTLCompileOptions alloc] init]; //opts.languageVersion = MTLLanguageVersion2_3; id &library = isVertexShader ? _vertLibrary : isFragmentShader ? _fragLibrary : _cmptLibrary; String shaderStage = isVertexShader ? "vertex" : isFragmentShader ? "fragment" : "compute"; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Sampler.h b/native/cocos/renderer/gfx-metal/MTLSwapchain.h similarity index 63% rename from native/cocos/renderer/gfx-gles2/GLES2Sampler.h rename to native/cocos/renderer/gfx-metal/MTLSwapchain.h index f40bce1cad..76ba92719c 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Sampler.h +++ b/native/cocos/renderer/gfx-metal/MTLSwapchain.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -24,39 +24,40 @@ ****************************************************************************/ #pragma once - -#include "gfx-base/GFXSampler.h" +#import +#import "gfx-base/GFXSwapchain.h" +#import "MTLTexture.h" namespace cc { namespace gfx { -class GLES2GPUSampler; +struct CCMTLGPUSwapChainObject; +class CCMTLTexture; -class CC_GLES2_API GLES2Sampler final : public Sampler { +class CCMTLSwapchain final : public Swapchain { public: - GLES2Sampler(); - ~GLES2Sampler(); + CCMTLSwapchain(); + ~CCMTLSwapchain(); - inline GLES2GPUSampler *gpuSampler() const { return _gpuSampler; } + inline CCMTLGPUSwapChainObject* gpuSwapChainObj() { return _gpuSwapchainObj; } + CCMTLTexture* colorTexture(); + CCMTLTexture* depthStencilTexture(); + + id currentDrawable(); + + void acquire(); + + void release(); protected: - void doInit(const SamplerInfo &info) override; + void doInit(const SwapchainInfo &info) override; void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; - GLES2GPUSampler *_gpuSampler = nullptr; - String _name; - Filter _minFilter = Filter::LINEAR; - Filter _magFilter = Filter::LINEAR; - Filter _mipFilter = Filter::NONE; - Address _addressU = Address::WRAP; - Address _addressV = Address::WRAP; - Address _addressW = Address::WRAP; - uint _maxAnisotropy = 16; - ComparisonFunc _cmpFunc = ComparisonFunc::NEVER; - Color _borderColor; - uint _minLOD = 0; - uint _maxLOD = 1000; - float _mipLODBias = 0.0f; +private: + CCMTLGPUSwapChainObject* _gpuSwapchainObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLSwapchain.mm b/native/cocos/renderer/gfx-metal/MTLSwapchain.mm new file mode 100644 index 0000000000..fbf656a425 --- /dev/null +++ b/native/cocos/renderer/gfx-metal/MTLSwapchain.mm @@ -0,0 +1,174 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#import "../gfx-base/GFXDef-common.h" +#import "MTLSwapchain.h" +#if CC_PLATFORM == CC_PLATFORM_MAC_OSX + #import +#else + #import +#endif + +#import "MTLGPUObjects.h" +#import "MTLDevice.h" +#import "MTLGPUObjects.h" +namespace cc { +namespace gfx { + +namespace { +#if CC_PLATFORM == CC_PLATFORM_MAC_OSX + using CCView = NSView; +#else + using CCView = UIView; +#endif +}; + +CCMTLSwapchain::CCMTLSwapchain() { +} + +CCMTLSwapchain::~CCMTLSwapchain() { + destroy(); +} + +void CCMTLSwapchain::doInit(const SwapchainInfo &info) { + _gpuSwapchainObj = CC_NEW(CCMTLGPUSwapChainObject); + + //----------------------acquire layer----------------------------------- + auto* view = (CCView*)info.windowHandle; + CAMetalLayer *layer = static_cast(view.layer); + + if (layer.pixelFormat == MTLPixelFormatInvalid) { + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + } + layer.framebufferOnly = NO; + //setDisplaySyncEnabled : physic device refresh rate. + //setPresentsWithTransaction : Core Animation transactions update rate. + switch (_vsyncMode) { + case VsyncMode::OFF: + [layer setDisplaySyncEnabled:NO]; + [layer setPresentsWithTransaction:NO]; + break; + case VsyncMode::ON: + [layer setDisplaySyncEnabled:YES]; + [layer setPresentsWithTransaction:YES]; + case VsyncMode::RELAXED: + case VsyncMode::MAILBOX: + case VsyncMode::HALF: + [layer setDisplaySyncEnabled:YES]; + [layer setPresentsWithTransaction:NO]; + default: + break; + } + _gpuSwapchainObj->mtlLayer = layer; + +// MTLPixelFormatBGRA8Unorm +// MTLPixelFormatBGRA8Unorm_sRGB +// MTLPixelFormatRGBA16Float +// MTLPixelFormatRGB10A2Unorm (macOS only) +// MTLPixelFormatBGR10A2Unorm (macOS only) +// MTLPixelFormatBGRA10_XR +// MTLPixelFormatBGRA10_XR_sRGB +// MTLPixelFormatBGR10_XR +// MTLPixelFormatBGR10_XR_sRGB + Format colorFmt = Format::BGRA8; + Format depthStencilFmt = Format::DEPTH_STENCIL; + + _colorTexture = CC_NEW(CCMTLTexture); + _depthStencilTexture = CC_NEW(CCMTLTexture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = colorFmt; + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = depthStencilFmt; + initTexture(textureInfo, _depthStencilTexture); + + CCMTLDevice::getInstance()->registerSwapchain(this); +} + +void CCMTLSwapchain::doDestroy(){ + CCMTLDevice::getInstance()->unRegisterSwapchain(this); + if(_gpuSwapchainObj) { + _gpuSwapchainObj->currentDrawable = nil; + _gpuSwapchainObj->mtlLayer = nil; + + CC_SAFE_DELETE(_gpuSwapchainObj); + } + + if(_colorTexture) { + CC_SAFE_DESTROY(_colorTexture); + } + + if(_depthStencilTexture) { + CC_SAFE_DESTROY(_depthStencilTexture); + } +} + +void CCMTLSwapchain::doDestroySurface() { + if(_gpuSwapchainObj) { + _gpuSwapchainObj->currentDrawable = nil; + _gpuSwapchainObj->mtlLayer = nil; + } +} + +void CCMTLSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform /*transform*/) { + _colorTexture->resize(width, height); + _depthStencilTexture->resize(width, height); +} + +CCMTLTexture* CCMTLSwapchain::colorTexture() { + return static_cast(_colorTexture); +} + +CCMTLTexture* CCMTLSwapchain::depthStencilTexture() { + return static_cast(_depthStencilTexture); +} + +id CCMTLSwapchain::currentDrawable() { + if(!_gpuSwapchainObj->currentDrawable) { + _gpuSwapchainObj->currentDrawable = [[_gpuSwapchainObj->mtlLayer nextDrawable] retain]; + } + return _gpuSwapchainObj->currentDrawable; +} + +void CCMTLSwapchain::release() { + _gpuSwapchainObj->currentDrawable = nil; +} + +void CCMTLSwapchain::acquire() { + // hang on here if next drawable not available + while(!currentDrawable()) { + ; + } +} + +void CCMTLSwapchain::doCreateSurface(void *windowHandle) { + +} + +} +} diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.h b/native/cocos/renderer/gfx-metal/MTLTexture.h index 8937607841..8e741f3ead 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.h +++ b/native/cocos/renderer/gfx-metal/MTLTexture.h @@ -25,13 +25,16 @@ #pragma once -#include "gfx-base/GFXTexture.h" +#import "gfx-base/GFXTexture.h" #import namespace cc { namespace gfx { +struct CCMTLGPUTextureObject; +class CCMTLSwapchain; + class CCMTLTexture final : public Texture { public: explicit CCMTLTexture(); @@ -41,23 +44,33 @@ public: CCMTLTexture &operator=(const CCMTLTexture &) = delete; CCMTLTexture &operator=(CCMTLTexture &&) = delete; - inline id getMTLTexture() const { return _mtlTexture; } + inline id getMTLTexture() const { + return _isTextureView ? _mtlTextureView : _mtlTexture; + } inline Format getConvertedFormat() const { return _convertedFormat; } inline bool isArray() const { return _isArray; } inline bool isPVRTC() const { return _isPVRTC; } + const TextureInfo& textureInfo(); + CCMTLSwapchain* swapChain(); protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; + void doInit(const SwapchainTextureInfo &info) override; bool createMTLTexture(); - id _mtlTexture = nil; + //update drawable from swapchain. + void update(); + Format _convertedFormat = Format::UNKNOWN; bool _isArray = false; bool _isPVRTC = false; + + id _mtlTexture = nil; + id _mtlTextureView = nil; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 54c9544aa4..ec5d8495da 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -23,12 +23,16 @@ THE SOFTWARE. ****************************************************************************/ -#include "MTLStd.h" +#import "MTLStd.h" -#include "MTLDevice.h" -#include "MTLGPUObjects.h" -#include "MTLTexture.h" -#include "MTLUtils.h" +#import "MTLDevice.h" +#import "MTLGPUObjects.h" +#import "MTLTexture.h" +#import "MTLUtils.h" +#import "MTLSwapchain.h" +#import +#import +#import namespace cc { namespace gfx { @@ -42,16 +46,53 @@ CCMTLTexture::~CCMTLTexture() { } void CCMTLTexture::doInit(const TextureInfo &info) { - _isArray = _type == TextureType::TEX1D_ARRAY || _type == TextureType::TEX2D_ARRAY; - if (_format == Format::PVRTC_RGB2 || - _format == Format::PVRTC_RGBA2 || - _format == Format::PVRTC_RGB4 || - _format == Format::PVRTC_RGBA4 || - _format == Format::PVRTC2_2BPP || - _format == Format::PVRTC2_4BPP) { + _isArray = _info.type == TextureType::TEX1D_ARRAY || info.type == TextureType::TEX2D_ARRAY; + if (_info.format == Format::PVRTC_RGB2 || + _info.format == Format::PVRTC_RGBA2 || + _info.format == Format::PVRTC_RGB4 || + _info.format == Format::PVRTC_RGBA4 || + _info.format == Format::PVRTC2_2BPP || + _info.format == Format::PVRTC2_4BPP) { _isPVRTC = true; } + if(_info.externalRes) { + auto pixelBuffer = static_cast(_info.externalRes); + size_t width = CVPixelBufferGetWidth(pixelBuffer); + size_t height = CVPixelBufferGetHeight(pixelBuffer); + + CVReturn cvret; + CVMetalTextureCacheRef CVMTLTextureCache; + cvret = CVMetalTextureCacheCreate( + kCFAllocatorDefault, + nil, + (id)CCMTLDevice::getInstance()->getMTLDevice(), + nil, + &CVMTLTextureCache); + + CCASSERT(cvret == kCVReturnSuccess, @"Failed to create Metal texture cache"); + + _convertedFormat = mu::convertGFXPixelFormat(_info.format); + MTLPixelFormat mtlFormat = mu::toMTLPixelFormat(_convertedFormat); + CVMetalTextureRef CVMTLTexture; + cvret = CVMetalTextureCacheCreateTextureFromImage( + kCFAllocatorDefault, + CVMTLTextureCache, + pixelBuffer, nil, + mtlFormat, + width, height, + 0, + &CVMTLTexture); + + CCASSERT(cvret == kCVReturnSuccess, @"Failed to create CoreVideo Metal texture from image"); + + _mtlTexture = CVMetalTextureGetTexture(CVMTLTexture); + CFRelease(CVMTLTexture); + CFRelease(CVMTLTextureCache); + + CCASSERT(_mtlTexture, @"Failed to create Metal texture CoreVideo Metal Texture"); + } + if (!createMTLTexture()) { CC_LOG_ERROR("CCMTLTexture: create MTLTexture failed."); return; @@ -61,47 +102,62 @@ void CCMTLTexture::doInit(const TextureInfo &info) { } void CCMTLTexture::doInit(const TextureViewInfo &info) { - _isArray = _type == TextureType::TEX1D_ARRAY || _type == TextureType::TEX2D_ARRAY; - if (_format == Format::PVRTC_RGB2 || - _format == Format::PVRTC_RGBA2 || - _format == Format::PVRTC_RGB4 || - _format == Format::PVRTC_RGBA4 || - _format == Format::PVRTC2_2BPP || - _format == Format::PVRTC2_4BPP) { + _isArray = info.type == TextureType::TEX1D_ARRAY || _viewInfo.type == TextureType::TEX2D_ARRAY; + if (_viewInfo.format == Format::PVRTC_RGB2 || + _viewInfo.format == Format::PVRTC_RGBA2 || + _viewInfo.format == Format::PVRTC_RGB4 || + _viewInfo.format == Format::PVRTC_RGBA4 || + _viewInfo.format == Format::PVRTC2_2BPP || + _viewInfo.format == Format::PVRTC2_4BPP) { _isPVRTC = true; } - _convertedFormat = mu::convertGFXPixelFormat(_format); - auto mtlTextureType = mu::toMTLTextureType(_type); - _mtlTexture = [id(info.texture) newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) - textureType:mtlTextureType - levels:NSMakeRange(info.baseLevel, info.levelCount) - slices:NSMakeRange(info.baseLayer, info.layerCount)]; + _convertedFormat = mu::convertGFXPixelFormat(_viewInfo.format); + auto mtlTextureType = mu::toMTLTextureType(_viewInfo.type); + _mtlTextureView = [id(_viewInfo.texture) newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) + textureType:mtlTextureType + levels:NSMakeRange(_viewInfo.baseLevel, _viewInfo.levelCount) + slices:NSMakeRange(_viewInfo.baseLayer, _viewInfo.layerCount)]; +} + +void CCMTLTexture::doInit(const SwapchainTextureInfo &info) { + _swapchain = info.swapchain; + if (info.format == Format::DEPTH_STENCIL) { + createMTLTexture(); + } else { + _mtlTexture = [static_cast(_swapchain)->currentDrawable() texture]; + } +} + +void CCMTLTexture::update() { + if(_swapchain) { + _mtlTexture = [static_cast(_swapchain)->gpuSwapChainObj()->currentDrawable texture]; + } } bool CCMTLTexture::createMTLTexture() { - if (_width == 0 || _height == 0) { + if (_info.width == 0 || _info.height == 0) { CC_LOG_ERROR("CCMTLTexture: width or height should not be zero."); return false; } - _convertedFormat = mu::convertGFXPixelFormat(_format); + _convertedFormat = mu::convertGFXPixelFormat(_info.format); MTLPixelFormat mtlFormat = mu::toMTLPixelFormat(_convertedFormat); if (mtlFormat == MTLPixelFormatInvalid) return false; MTLTextureDescriptor *descriptor = nullptr; - auto mtlTextureType = mu::toMTLTextureType(_type); + auto mtlTextureType = mu::toMTLTextureType(_info.type); switch (mtlTextureType) { case MTLTextureType2D: case MTLTextureType2DArray: // No need to set mipmapped flag since mipmapLevelCount was explicty set via `_levelCount`. descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:mtlFormat - width:_width - height:_height + width:_info.width + height:_info.height mipmapped:NO]; break; case MTLTextureTypeCube: descriptor = [MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:mtlFormat - size:_width + size:_info.width mipmapped:NO]; break; default: @@ -112,20 +168,20 @@ bool CCMTLTexture::createMTLTexture() { if (descriptor == nullptr) return false; - descriptor.usage = mu::toMTLTextureUsage(_usage); - descriptor.sampleCount = mu::toMTLSampleCount(_samples); - descriptor.textureType = descriptor.sampleCount > 1 ? MTLTextureType2DMultisample : mu::toMTLTextureType(_type); - descriptor.mipmapLevelCount = _levelCount; - descriptor.arrayLength = _type == TextureType::CUBE ? 1 : _layerCount; - - if(hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _usage) && mu::isImageBlockSupported()) { + descriptor.usage = mu::toMTLTextureUsage(_info.usage); + descriptor.sampleCount = mu::toMTLSampleCount(_info.samples); + descriptor.textureType = descriptor.sampleCount > 1 ? MTLTextureType2DMultisample : mu::toMTLTextureType(_info.type); + descriptor.mipmapLevelCount = _info.levelCount; + descriptor.arrayLength = _info.type == TextureType::CUBE ? 1 : _info.layerCount; + + if(hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _info.usage) && mu::isImageBlockSupported()) { //xcode OS version warning if (@available(macOS 11.0, *)) { descriptor.storageMode = MTLStorageModeMemoryless; } else { descriptor.storageMode = MTLStorageModePrivate; } - } else if (hasFlag(_usage, TextureUsage::COLOR_ATTACHMENT) || hasFlag(_usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT) || hasFlag(_usage, TextureUsage::INPUT_ATTACHMENT)) { + } else if (hasFlag(_info.usage, TextureUsage::COLOR_ATTACHMENT) || hasFlag(_info.usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT) || hasFlag(_info.usage, TextureUsage::INPUT_ATTACHMENT)) { descriptor.storageMode = MTLStorageModePrivate; } @@ -135,17 +191,35 @@ bool CCMTLTexture::createMTLTexture() { return _mtlTexture != nil; } +CCMTLSwapchain* CCMTLTexture::swapChain() { + return static_cast(_swapchain); +} + +const TextureInfo& CCMTLTexture::textureInfo() { + return _isTextureView ? + static_cast(_viewInfo.texture)->_info : + _info; +} + void CCMTLTexture::doDestroy() { - if (_isTextureView) { + if(_swapchain) { + _swapchain = nullptr; + _mtlTexture = nil; return; } + id mtlTexure = nil; + if(_isTextureView) { + mtlTexure = _mtlTextureView; + _mtlTextureView = nil; + } else { + mtlTexure = _mtlTexture; + _mtlTexture = nil; + } + CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= _size; - id mtlTexure = _mtlTexture; - _mtlTexture = nil; - - std::function destroyFunc = [=]() { + std::function destroyFunc = [mtlTexure]() { if (mtlTexure) { [mtlTexure setPurgeableState:MTLPurgeableStateEmpty]; [mtlTexure release]; @@ -156,17 +230,22 @@ void CCMTLTexture::doDestroy() { } void CCMTLTexture::doResize(uint width, uint height, uint size) { + if(_isTextureView) { + CC_LOG_ERROR("TextureView does not support resize! at %p", this); + return; + } auto oldSize = _size; - auto oldWidth = _width; - auto oldHeight = _height; + auto oldWidth = _info.width; + auto oldHeight = _info.height; + id oldMTLTexture = _mtlTexture; - _width = width; - _height = height; + _info.width = width; + _info.height = height; _size = size; if (!createMTLTexture()) { - _width = oldWidth; - _height = oldHeight; + _info.width = oldWidth; + _info.height = oldHeight; _size = oldSize; _mtlTexture = oldMTLTexture; CC_LOG_ERROR("CCMTLTexture: create MTLTexture failed when try to resize the texture."); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index a3e0ce725d..4e4d92f279 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -69,7 +69,7 @@ MTLSamplerAddressMode toMTLSamplerAddressMode(Address); int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -String compileGLSLShader2Msl(const String &src, ShaderStageFlagBit shaderType, Device *device, CCMTLGPUShader *gpuShader); +String spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader); const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint length); const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint length); NSUInteger highestSupportedFeatureSet(id device); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 57a3b1398d..8b41cee962 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -82,53 +82,7 @@ glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { } } -const vector GLSL2SPIRV(ShaderStageFlagBit type, const String &source, int vulkanMinorVersion = 2) { - static bool glslangInitialized = false; - if (!glslangInitialized) { - glslang::InitializeProcess(); - glslangInitialized = true; - } - vector spirv; - auto stage = getShaderStage(type); - auto string = source.c_str(); - glslang::TShader shader(stage); - shader.setStrings(&string, 1); - //Set up Vulkan/SpirV Environment - int clientInputSemanticsVersion = 100 + vulkanMinorVersion * 10; // maps to, say, #define VULKAN 120 - glslang::EShTargetClientVersion clientVersion = getClientVersion(vulkanMinorVersion); // map to, say, Vulkan 1.2 - glslang::EShTargetLanguageVersion targetVersion = getTargetVersion(vulkanMinorVersion); // maps to, say, SPIR-V 1.5 - - shader.setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientVulkan, clientInputSemanticsVersion); - shader.setEnvClient(glslang::EShClientVulkan, clientVersion); - shader.setEnvTarget(glslang::EShTargetSpv, targetVersion); - - EShMessages messages = EShMsgRelaxedErrors; - - if (!shader.parse(&glslang::DefaultTBuiltInResource, clientInputSemanticsVersion, false, messages)) { - CC_LOG_ERROR("GLSL Parsing Failed:\n%s\n%s", shader.getInfoLog(), shader.getInfoDebugLog()); - CC_LOG_ERROR("%s", string); - return spirv; - } - glslang::TProgram program; - program.addShader(&shader); - - if (!program.link(messages)) { - CC_LOG_ERROR("GLSL Linking Failed:\n%s\n%s", program.getInfoLog(), program.getInfoDebugLog()); - CC_LOG_ERROR("%s", string); - return spirv; - } - - spv::SpvBuildLogger logger; - glslang::SpvOptions spvOptions; - glslang::GlslangToSpv(*program.getIntermediate(stage), spirv, &logger, &spvOptions); - if (!spirv.size()) { - CC_LOG_ERROR("GlslangToSpv Failed:\n%s\n%s", program.getInfoLog(), program.getInfoDebugLog()); - CC_LOG_ERROR("%s", string); - return spirv; - } - return spirv; -} //See more details at https://developer.apple.com/documentation/metal/mtlfeatureset enum class GPUFamily { @@ -654,27 +608,30 @@ MTLPixelFormat mu::toMTLPixelFormat(Format format) { case Format::RGB9E5: return MTLPixelFormatRGB9E5Float; case Format::RGB10A2UI: return MTLPixelFormatRGB10A2Uint; case Format::R11G11B10F: return MTLPixelFormatRG11B10Float; - case Format::D16: { +// case Format::D16: { +//#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) +// return MTLPixelFormatDepth16Unorm; +//#else +// if (@available(iOS 13.0, *)) +// return MTLPixelFormatDepth16Unorm; +// else +// break; +//#endif +// } + case Format::DEPTH: return MTLPixelFormatDepth32Float; #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - return MTLPixelFormatDepth16Unorm; -#else - if (@available(iOS 13.0, *)) - return MTLPixelFormatDepth16Unorm; - else - break; -#endif - } - case Format::D32F: return MTLPixelFormatDepth32Float; - case Format::D32F_S8: return MTLPixelFormatDepth32Float_Stencil8; -#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - case Format::D24S8: return MTLPixelFormatDepth24Unorm_Stencil8; + case Format::DEPTH_STENCIL: return MTLPixelFormatDepth24Unorm_Stencil8; + case Format::BC1: case Format::BC1_ALPHA: return MTLPixelFormatBC1_RGBA; case Format::BC1_SRGB_ALPHA: return MTLPixelFormatBC1_RGBA_sRGB; case Format::BC2: return MTLPixelFormatBC2_RGBA; case Format::BC2_SRGB: return MTLPixelFormatBC2_RGBA_sRGB; case Format::BC3: return MTLPixelFormatBC3_RGBA; case Format::BC3_SRGB: return MTLPixelFormatBC3_RGBA_sRGB; + case Format::BC4: return MTLPixelFormatBC4_RUnorm; + case Format::BC4_SNORM: return MTLPixelFormatBC4_RSnorm; #else + case Format::DEPTH_STENCIL: return MTLPixelFormatDepth32Float_Stencil8; case Format::ASTC_RGBA_4X4: return MTLPixelFormatASTC_4x4_LDR; case Format::ASTC_RGBA_5X4: return MTLPixelFormatASTC_5x4_LDR; case Format::ASTC_RGBA_5X5: return MTLPixelFormatASTC_5x5_LDR; @@ -903,14 +860,15 @@ MTLTextureType mu::toMTLTextureType(TextureType type) { } NSUInteger mu::toMTLSampleCount(SampleCount count) { + //TODO_Zeqiang: query from device. switch (count) { - case SampleCount::X1: return 1; - case SampleCount::X2: return 2; - case SampleCount::X4: return 4; - case SampleCount::X8: return 8; - case SampleCount::X16: return 16; - case SampleCount::X32: return 32; - case SampleCount::X64: return 64; + case SampleCount::ONE: return 1; + case SampleCount::MULTIPLE_PERFORMANCE: return 2; + case SampleCount::MULTIPLE_BALANCE: return 4; + case SampleCount::MULTIPLE_QUALITY: return 8; +// case SampleCount::X16: return 16; +// case SampleCount::X32: return 32; +// case SampleCount::X64: return 64; } } @@ -979,18 +937,11 @@ bool mu::isFramebufferFetchSupported() { #endif } -String mu::compileGLSLShader2Msl(const String &src, - ShaderStageFlagBit shaderType, - Device *device, - CCMTLGPUShader *gpuShader) { -#if CC_USE_METAL - String shaderSource("#version 460\n"); - shaderSource.append(src); - const auto &spv = GLSL2SPIRV(shaderType, shaderSource); - if (spv.size() == 0) - return ""; - - spirv_cross::CompilerMSL msl(std::move(spv)); +String mu::spirv2MSL(const uint32_t *ir, size_t word_count, + ShaderStageFlagBit shaderType, + CCMTLGPUShader *gpuShader) { + CCMTLDevice* device = CCMTLDevice::getInstance(); + spirv_cross::CompilerMSL msl(ir, word_count); // The SPIR-V is now parsed, and we can perform reflection on it. auto executionModel = msl.get_execution_model(); @@ -1020,7 +971,7 @@ String mu::compileGLSLShader2Msl(const String &src, // TODO: bindings from shader just kind of validation, cannot be directly input // Get all uniform buffers in the shader. - uint maxBufferBindingIndex = static_cast(device)->getMaximumBufferBindingIndex(); + uint maxBufferBindingIndex = device->getMaximumBufferBindingIndex(); const auto &bufferBindingOffset = device->bindingMappingInfo().bufferOffsets; for (const auto &ubo : resources.uniform_buffers) { auto set = msl.get_decoration(ubo.id, spv::DecorationDescriptorSet); @@ -1069,8 +1020,8 @@ String mu::compileGLSLShader2Msl(const String &src, } //TODO: coulsonwang, need to set sampler binding explicitly - if (resources.sampled_images.size() > static_cast(device)->getMaximumSamplerUnits()) { - CC_LOG_ERROR("Implementation limits: Should not use more than %d entries in the sampler state argument table", static_cast(device)->getMaximumSamplerUnits()); + if (resources.sampled_images.size() > device->getMaximumSamplerUnits()) { + CC_LOG_ERROR("Implementation limits: Should not use more than %d entries in the sampler state argument table", device->getMaximumSamplerUnits()); return ""; } @@ -1145,13 +1096,9 @@ String mu::compileGLSLShader2Msl(const String &src, } if (!output.size()) { CC_LOG_ERROR("Compile to MSL failed."); - CC_LOG_ERROR("%s", shaderSource.c_str()); + CC_LOG_ERROR("%s", output.c_str()); } return output; - -#else - return src; -#endif } const uint8_t *mu::convertRGB8ToRGBA8(const uint8_t *source, uint length) { @@ -1491,47 +1438,48 @@ bool mu::isIndirectCommandBufferSupported(MTLFeatureSet featureSet) { return false; } bool mu::isDepthStencilFormatSupported(id device, Format format, uint family) { - GPUFamily gpuFamily = static_cast(family); - switch (format) { - case Format::D16: - switch (gpuFamily) { - case GPUFamily::Apple1: - case GPUFamily::Apple2: - case GPUFamily::Apple3: - case GPUFamily::Apple4: - case GPUFamily::Apple5: - case GPUFamily::Apple6: - case GPUFamily::Mac1: - case GPUFamily::Mac2: - return true; - } - case Format::D32F: - case Format::D32F_S8: - switch (gpuFamily) { - case GPUFamily::Apple1: - case GPUFamily::Apple2: - case GPUFamily::Apple3: - case GPUFamily::Apple4: - case GPUFamily::Apple5: - case GPUFamily::Apple6: -#ifdef TARGET_OS_SIMULATOR - return true; -#else - return false; -#endif - case GPUFamily::Mac1: - case GPUFamily::Mac2: - return true; - } - case Format::D24S8: -#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - return [device isDepth24Stencil8PixelFormatSupported]; -#else - return false; -#endif - default: - return false; - } + return true; +// GPUFamily gpuFamily = static_cast(family); +// switch (format) { +// case Format::D16: +// switch (gpuFamily) { +// case GPUFamily::Apple1: +// case GPUFamily::Apple2: +// case GPUFamily::Apple3: +// case GPUFamily::Apple4: +// case GPUFamily::Apple5: +// case GPUFamily::Apple6: +// case GPUFamily::Mac1: +// case GPUFamily::Mac2: +// return true; +// } +// case Format::D32F: +// case Format::D32F_S8: +// switch (gpuFamily) { +// case GPUFamily::Apple1: +// case GPUFamily::Apple2: +// case GPUFamily::Apple3: +// case GPUFamily::Apple4: +// case GPUFamily::Apple5: +// case GPUFamily::Apple6: +//#ifdef TARGET_OS_SIMULATOR +// return true; +//#else +// return false; +//#endif +// case GPUFamily::Mac1: +// case GPUFamily::Mac2: +// return true; +// } +// case Format::D24S8: +//#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) +// return [device isDepth24Stencil8PixelFormatSupported]; +//#else +// return false; +//#endif +// default: +// return false; +// } } bool mu::isIndirectDrawSupported(uint family) { @@ -1543,16 +1491,11 @@ bool mu::isIndirectDrawSupported(uint family) { } MTLPixelFormat mu::getSupportedDepthStencilFormat(id device, uint family, uint &depthBits) { - vector> formats = {{Format::D24S8, 24}, {Format::D32F_S8, 32}, {Format::D16S8, 16}}; - Format format; - for (const auto &formatPair : formats) { - std::tie(format, depthBits) = formatPair; - if (isDepthStencilFormatSupported(device, format, family)) - return toMTLPixelFormat(format); - else - continue; - } - return MTLPixelFormatInvalid; +#if CC_PLATFORM == CC_PLATFORM_MAC_OSX + return MTLPixelFormatDepth24Unorm_Stencil8; +#else + return MTLPixelFormatDepth32Float_Stencil8; +#endif } String mu::featureSetToString(MTLFeatureSet featureSet) { diff --git a/native/cocos/renderer/gfx-validator/BufferValidator.cpp b/native/cocos/renderer/gfx-validator/BufferValidator.cpp index 5f78d246e2..3649533f14 100644 --- a/native/cocos/renderer/gfx-validator/BufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/BufferValidator.cpp @@ -24,30 +24,47 @@ ****************************************************************************/ #include "base/CoreStd.h" +#include "base/Log.h" +#include "base/Macros.h" #include "base/threading/MessageQueue.h" +#include "bindings/jswrapper/SeApi.h" + #include "BufferValidator.h" #include "DeviceValidator.h" #include "ValidationUtils.h" +#include "gfx-base/GFXDef-common.h" namespace cc { namespace gfx { BufferValidator::BufferValidator(Buffer *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } BufferValidator::~BufferValidator() { DeviceResourceTracker::erase(this); CC_SAFE_DELETE(_actor); + + uint lifeTime = DeviceValidator::getInstance()->currentFrame() - _creationFrame; + // skip those that have never been updated + if (!_isBufferView && hasFlag(_memUsage, MemoryUsageBit::HOST) && _totalUpdateTimes && _totalUpdateTimes < lifeTime / 3) { + CC_LOG_WARNING("Triple buffer enabled for infrequently-updated buffer, consider using MemoryUsageBit::DEVICE instead"); + CC_LOG_DEBUG("Init Stacktrace: %s", _initStack.c_str()); + } } void BufferValidator::doInit(const BufferInfo &info) { - CCASSERT(info.usage != BufferUsageBit::NONE, "invalid source buffer"); - CCASSERT(info.memUsage != MemoryUsageBit::NONE, "invalid source buffer"); + CCASSERT(info.usage != BufferUsageBit::NONE, "invalid buffer param"); + CCASSERT(info.memUsage != MemoryUsageBit::NONE, "invalid buffer param"); // CCASSERT(info.size, "zero-sized buffer?"); // be more lenient on this for now + _initStack = se::ScriptEngine::getInstance()->getCurrentStackTrace(); + + _creationFrame = DeviceValidator::getInstance()->currentFrame(); + _totalUpdateTimes = 0U; + if (hasFlag(info.usage, BufferUsageBit::VERTEX) && !info.stride) { CCASSERT(false, "invalid stride for vertex buffer"); } @@ -99,6 +116,7 @@ void BufferValidator::update(const void *buffer, uint size) { } sanityCheck(buffer, size); + ++_totalUpdateTimes; // only count direct updates /////////// execute /////////// diff --git a/native/cocos/renderer/gfx-validator/BufferValidator.h b/native/cocos/renderer/gfx-validator/BufferValidator.h index 83bf7b4285..7cd45dd99e 100644 --- a/native/cocos/renderer/gfx-validator/BufferValidator.h +++ b/native/cocos/renderer/gfx-validator/BufferValidator.h @@ -48,7 +48,11 @@ protected: vector _buffer; - uint _lastUpdateFrame = 0U; + uint _lastUpdateFrame{0U}; + uint _totalUpdateTimes{0U}; + uint _creationFrame{0U}; + + String _initStack; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index 5e85a39472..835bff3882 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -37,10 +37,16 @@ #include "RenderPassValidator.h" #include "TextureValidator.h" #include "ValidationUtils.h" +#include "gfx-base/GFXCommandBuffer.h" namespace cc { namespace gfx { +CommandBufferValidator::CommandBufferValidator(CommandBuffer *actor) +: Agent(actor) { + _typedID = actor->getTypedID(); +} + CommandBufferValidator::~CommandBufferValidator() { DeviceResourceTracker::erase(this); CC_SAFE_DELETE(_actor); diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index da3390b4f7..b4f2bb7f78 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -35,7 +35,7 @@ namespace gfx { class CC_DLL CommandBufferValidator final : public Agent { public: - using Agent::Agent; + explicit CommandBufferValidator(CommandBuffer *actor); ~CommandBufferValidator() override; void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp index f3aaa9ba3d..0cc1edfd43 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetLayoutValidator.cpp @@ -35,7 +35,7 @@ namespace gfx { DescriptorSetLayoutValidator::DescriptorSetLayoutValidator(DescriptorSetLayout *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } DescriptorSetLayoutValidator::~DescriptorSetLayoutValidator() { diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp index 0e410604da..3e009b877d 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp @@ -30,7 +30,6 @@ #include "DescriptorSetLayoutValidator.h" #include "DescriptorSetValidator.h" #include "DeviceValidator.h" -#include "SamplerValidator.h" #include "TextureValidator.h" #include "ValidationUtils.h" @@ -39,7 +38,7 @@ namespace gfx { DescriptorSetValidator::DescriptorSetValidator(DescriptorSet *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } DescriptorSetValidator::~DescriptorSetValidator() { @@ -114,7 +113,7 @@ void DescriptorSetValidator::bindSampler(uint binding, Sampler *sampler, uint in DescriptorSet::bindSampler(binding, sampler, index); - _actor->bindSampler(binding, static_cast(sampler)->getActor(), index); + _actor->bindSampler(binding, sampler, index); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 7993cdcfef..45fa397803 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -36,10 +36,11 @@ #include "PipelineStateValidator.h" #include "QueueValidator.h" #include "RenderPassValidator.h" -#include "SamplerValidator.h" #include "ShaderValidator.h" +#include "SwapchainValidator.h" #include "TextureValidator.h" #include "ValidationUtils.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { @@ -64,19 +65,17 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { return false; } - _context = _actor->getContext(); - _api = _actor->getGfxAPI(); - _deviceName = _actor->getDeviceName(); - _queue = CC_NEW(QueueValidator(_actor->getQueue())); - auto *cmdBuffValidator = CC_NEW(CommandBufferValidator(_actor->getCommandBuffer())); - _cmdBuff = cmdBuffValidator; - cmdBuffValidator->_queue = _queue; - _renderer = _actor->getRenderer(); - _vendor = _actor->getVendor(); - _caps = _actor->_caps; - + _api = _actor->getGfxAPI(); + _deviceName = _actor->getDeviceName(); + _queue = CC_NEW(QueueValidator(_actor->getQueue())); + _cmdBuff = CC_NEW(CommandBufferValidator(_actor->getCommandBuffer())); + _renderer = _actor->getRenderer(); + _vendor = _actor->getVendor(); + _caps = _actor->_caps; memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); - cmdBuffValidator->initValidator(); + + static_cast(_cmdBuff)->_queue = _queue; + static_cast(_cmdBuff)->initValidator(); DeviceResourceTracker::push(_cmdBuff); DeviceResourceTracker::push(_queue); @@ -100,6 +99,7 @@ void DeviceValidator::doDestroy() { DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); + DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); @@ -115,16 +115,21 @@ void DeviceValidator::doDestroy() { _actor->destroy(); } -void DeviceValidator::resize(uint width, uint height) { - _actor->resize(width, height); -} +void DeviceValidator::acquire(Swapchain *const *swapchains, uint32_t count) { + static vector swapchainActors; + swapchainActors.resize(count); -void DeviceValidator::acquire() { - _actor->acquire(); + for (uint i = 0U; i < count; ++i) { + auto *swapchain = static_cast(swapchains[i]); + swapchainActors[i] = swapchain->getActor(); + } + + _actor->acquire(swapchainActors.data(), count); } void DeviceValidator::present() { _actor->present(); + ++_currentFrame; } @@ -142,6 +147,13 @@ Queue *DeviceValidator::createQueue() { return result; } +Swapchain *DeviceValidator::createSwapchain() { + Swapchain *actor = _actor->createSwapchain(); + Swapchain *result = CC_NEW(SwapchainValidator(actor)); + DeviceResourceTracker::push(result); + return result; +} + Buffer *DeviceValidator::createBuffer() { Buffer *actor = _actor->createBuffer(); Buffer *result = CC_NEW(BufferValidator(actor)); @@ -156,13 +168,6 @@ Texture *DeviceValidator::createTexture() { return result; } -Sampler *DeviceValidator::createSampler() { - Sampler *actor = _actor->createSampler(); - Sampler *result = CC_NEW(SamplerValidator(actor)); - DeviceResourceTracker::push(result); - return result; -} - Shader *DeviceValidator::createShader() { Shader *actor = _actor->createShader(); Shader *result = CC_NEW(ShaderValidator(actor)); @@ -219,14 +224,16 @@ PipelineState *DeviceValidator::createPipelineState() { return result; } -GlobalBarrier *DeviceValidator::createGlobalBarrier() { - GlobalBarrier *actor = _actor->createGlobalBarrier(); - return actor; +Sampler *DeviceValidator::createSampler(const SamplerInfo &info) { + return _actor->createSampler(info); } -TextureBarrier *DeviceValidator::createTextureBarrier() { - TextureBarrier *actor = _actor->createTextureBarrier(); - return actor; +GlobalBarrier *DeviceValidator::createGlobalBarrier(const GlobalBarrierInfo &info) { + return _actor->createGlobalBarrier(info); +} + +TextureBarrier *DeviceValidator::createTextureBarrier(const TextureBarrierInfo &info) { + return _actor->createTextureBarrier(info); } void DeviceValidator::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index e965fddaf4..841fbbf11a 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -54,15 +54,14 @@ public: using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -71,19 +70,19 @@ public: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; - void flushCommands(CommandBuffer *const *cmdBuffs, uint count) override; - SurfaceTransform getSurfaceTransform() const override { return _actor->getSurfaceTransform(); } - uint getWidth() const override { return _actor->getWidth(); } - uint getHeight() const override { return _actor->getHeight(); } - MemoryStatus & getMemoryStatus() override { return _actor->getMemoryStatus(); } - uint getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } - uint getNumInstances() const override { return _actor->getNumInstances(); } - uint getNumTris() const override { return _actor->getNumTris(); } + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; + + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + + void flushCommands(CommandBuffer *const *cmdBuffs, uint count) override; + MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } + uint getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } + uint getNumInstances() const override { return _actor->getNumInstances(); } + uint getNumTris() const override { return _actor->getNumTris(); } inline void enableRecording(bool recording) { _recording = recording; } inline bool isRecording() const { return _recording; } @@ -99,11 +98,7 @@ protected: bool doInit(const DeviceInfo &info) override; void doDestroy() override; - void releaseSurface(uintptr_t windowHandle) override { _actor->releaseSurface(windowHandle); } - void acquireSurface(uintptr_t windowHandle) override { _actor->acquireSurface(windowHandle); } - - void bindRenderContext(bool bound) override { _actor->bindRenderContext(bound); } - void bindDeviceContext(bool bound) override { _actor->bindDeviceContext(bound); } + void bindContext(bool bound) override { _actor->bindContext(bound); } bool _recording{false}; uint _currentFrame{1U}; diff --git a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp index 63762bbf7b..59c9572353 100644 --- a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp @@ -37,7 +37,7 @@ namespace gfx { FramebufferValidator::FramebufferValidator(Framebuffer *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } FramebufferValidator::~FramebufferValidator() { diff --git a/native/cocos/renderer/gfx-validator/InputAssemblerValidator.cpp b/native/cocos/renderer/gfx-validator/InputAssemblerValidator.cpp index 42e795a54a..d7bc0cc13d 100644 --- a/native/cocos/renderer/gfx-validator/InputAssemblerValidator.cpp +++ b/native/cocos/renderer/gfx-validator/InputAssemblerValidator.cpp @@ -36,7 +36,7 @@ namespace gfx { InputAssemblerValidator::InputAssemblerValidator(InputAssembler *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } InputAssemblerValidator::~InputAssemblerValidator() { @@ -63,44 +63,44 @@ void InputAssemblerValidator::doDestroy() { _actor->destroy(); } -void InputAssemblerValidator::setVertexCount(uint count) { - _vertexCount = count; +void InputAssemblerValidator::setVertexCount(uint32_t count) { + _drawInfo.vertexCount = count; _actor->setVertexCount(count); } -void InputAssemblerValidator::setFirstVertex(uint first) { - _firstVertex = first; +void InputAssemblerValidator::setFirstVertex(uint32_t first) { + _drawInfo.firstVertex = first; _actor->setFirstVertex(first); } -void InputAssemblerValidator::setIndexCount(uint count) { - _indexCount = count; +void InputAssemblerValidator::setIndexCount(uint32_t count) { + _drawInfo.indexCount = count; _actor->setIndexCount(count); } -void InputAssemblerValidator::setFirstIndex(uint first) { - _firstIndex = first; +void InputAssemblerValidator::setFirstIndex(uint32_t first) { + _drawInfo.firstIndex = first; _actor->setFirstIndex(first); } -void InputAssemblerValidator::setVertexOffset(uint offset) { - _vertexOffset = offset; +void InputAssemblerValidator::setVertexOffset(int32_t offset) { + _drawInfo.vertexOffset = offset; _actor->setVertexOffset(offset); } -void InputAssemblerValidator::setInstanceCount(uint count) { - _instanceCount = count; +void InputAssemblerValidator::setInstanceCount(uint32_t count) { + _drawInfo.instanceCount = count; _actor->setInstanceCount(count); } -void InputAssemblerValidator::setFirstInstance(uint first) { - _firstInstance = first; +void InputAssemblerValidator::setFirstInstance(uint32_t first) { + _drawInfo.firstInstance = first; _actor->setFirstInstance(first); } diff --git a/native/cocos/renderer/gfx-validator/InputAssemblerValidator.h b/native/cocos/renderer/gfx-validator/InputAssemblerValidator.h index 46560c95cc..444f863aa8 100644 --- a/native/cocos/renderer/gfx-validator/InputAssemblerValidator.h +++ b/native/cocos/renderer/gfx-validator/InputAssemblerValidator.h @@ -36,13 +36,13 @@ public: explicit InputAssemblerValidator(InputAssembler *actor); ~InputAssemblerValidator() override; - void setVertexCount(uint count) override; - void setFirstVertex(uint first) override; - void setIndexCount(uint count) override; - void setFirstIndex(uint first) override; - void setVertexOffset(uint offset) override; - void setInstanceCount(uint count) override; - void setFirstInstance(uint first) override; + void setVertexCount(uint32_t count) override; + void setFirstVertex(uint32_t first) override; + void setIndexCount(uint32_t count) override; + void setFirstIndex(uint32_t first) override; + void setVertexOffset(int32_t offset) override; + void setInstanceCount(uint32_t count) override; + void setFirstInstance(uint32_t first) override; protected: void doInit(const InputAssemblerInfo &info) override; diff --git a/native/cocos/renderer/gfx-validator/PipelineLayoutValidator.cpp b/native/cocos/renderer/gfx-validator/PipelineLayoutValidator.cpp index 5b9ef0330b..08f977154b 100644 --- a/native/cocos/renderer/gfx-validator/PipelineLayoutValidator.cpp +++ b/native/cocos/renderer/gfx-validator/PipelineLayoutValidator.cpp @@ -36,7 +36,7 @@ namespace gfx { PipelineLayoutValidator::PipelineLayoutValidator(PipelineLayout *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } PipelineLayoutValidator::~PipelineLayoutValidator() { diff --git a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp index ca77af50a1..aed4fbfcc7 100644 --- a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp +++ b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp @@ -38,7 +38,7 @@ namespace gfx { PipelineStateValidator::PipelineStateValidator(PipelineState *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } PipelineStateValidator::~PipelineStateValidator() { diff --git a/native/cocos/renderer/gfx-validator/QueueValidator.cpp b/native/cocos/renderer/gfx-validator/QueueValidator.cpp index 7cb77730ad..7e66b4c752 100644 --- a/native/cocos/renderer/gfx-validator/QueueValidator.cpp +++ b/native/cocos/renderer/gfx-validator/QueueValidator.cpp @@ -35,7 +35,7 @@ namespace gfx { QueueValidator::QueueValidator(Queue *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } QueueValidator::~QueueValidator() { diff --git a/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp b/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp index d3fa3d01e9..1d995f5ca1 100644 --- a/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp +++ b/native/cocos/renderer/gfx-validator/RenderPassValidator.cpp @@ -35,7 +35,7 @@ namespace gfx { RenderPassValidator::RenderPassValidator(RenderPass *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } RenderPassValidator::~RenderPassValidator() { @@ -44,6 +44,14 @@ RenderPassValidator::~RenderPassValidator() { } void RenderPassValidator::doInit(const RenderPassInfo &info) { + bool hasDepth = info.depthStencilAttachment.format != Format::UNKNOWN; + if (!hasDepth) { + for (const auto &subpass : info.subpasses) { + CCASSERT(subpass.depthStencil == INVALID_BINDING || subpass.depthStencil < info.colorAttachments.size(), + "Invalid depth stencil attachment index"); + } + } + _actor->initialize(info); } diff --git a/native/cocos/renderer/gfx-validator/ShaderValidator.cpp b/native/cocos/renderer/gfx-validator/ShaderValidator.cpp index 33194a14bf..938bb288ae 100644 --- a/native/cocos/renderer/gfx-validator/ShaderValidator.cpp +++ b/native/cocos/renderer/gfx-validator/ShaderValidator.cpp @@ -35,7 +35,7 @@ namespace gfx { ShaderValidator::ShaderValidator(Shader *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } ShaderValidator::~ShaderValidator() { diff --git a/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp b/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp new file mode 100644 index 0000000000..f45a6ccf66 --- /dev/null +++ b/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "base/CoreStd.h" + +#include "SwapchainValidator.h" +#include "ValidationUtils.h" +#include "gfx-base/GFXDef.h" +#include "gfx-validator/DeviceValidator.h" +#include "gfx-validator/TextureValidator.h" + +namespace cc { +namespace gfx { + +SwapchainValidator::SwapchainValidator(Swapchain *actor) +: Agent(actor) { + _typedID = actor->getTypedID(); +} + +SwapchainValidator::~SwapchainValidator() { + CC_SAFE_DELETE(_depthStencilTexture); + CC_SAFE_DELETE(_colorTexture); + + DeviceResourceTracker::erase(this); + CC_SAFE_DELETE(_actor); +} + +void SwapchainValidator::doInit(const SwapchainInfo &info) { + _actor->initialize(info); + + auto *colorTexture = CC_NEW(TextureValidator(_actor->getColorTexture())); + colorTexture->renounceOwnership(); + _colorTexture = colorTexture; + DeviceResourceTracker::push(_colorTexture); + + auto *depthStencilTexture = CC_NEW(TextureValidator(_actor->getDepthStencilTexture())); + depthStencilTexture->renounceOwnership(); + _depthStencilTexture = depthStencilTexture; + DeviceResourceTracker::push(_depthStencilTexture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = _actor->getColorTexture()->getFormat(); + textureInfo.width = info.width; + textureInfo.height = info.height; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = _actor->getDepthStencilTexture()->getFormat(); + initTexture(textureInfo, _depthStencilTexture); +} + +void SwapchainValidator::doDestroy() { + CC_SAFE_DELETE(_depthStencilTexture); + CC_SAFE_DELETE(_colorTexture); + + _actor->destroy(); +} + +void SwapchainValidator::doResize(uint32_t width, uint32_t height, SurfaceTransform transform) { + _actor->resize(width, height, transform); +} + +void SwapchainValidator::doDestroySurface() { + _actor->destroySurface(); +} + +void SwapchainValidator::doCreateSurface(void *windowHandle) { + _actor->createSurface(windowHandle); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptySampler.h b/native/cocos/renderer/gfx-validator/SwapchainValidator.h similarity index 74% rename from native/cocos/renderer/gfx-empty/EmptySampler.h rename to native/cocos/renderer/gfx-validator/SwapchainValidator.h index b09dc12044..f7bf74663b 100644 --- a/native/cocos/renderer/gfx-empty/EmptySampler.h +++ b/native/cocos/renderer/gfx-validator/SwapchainValidator.h @@ -25,16 +25,25 @@ #pragma once -#include "gfx-base/GFXSampler.h" +#include "base/Agent.h" +#include "gfx-base/GFXSwapchain.h" namespace cc { namespace gfx { -class CC_DLL EmptySampler final : public Sampler { +class CC_DLL SwapchainValidator final : public Agent { public: + explicit SwapchainValidator(Swapchain *actor); + ~SwapchainValidator() override; + + bool isPreRotationEnabled() override { return _actor->isPreRotationEnabled(); } + protected: - void doInit(const SamplerInfo &info) override; + void doInit(const SwapchainInfo &info) override; void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-validator/TextureValidator.cpp b/native/cocos/renderer/gfx-validator/TextureValidator.cpp index b991d37cab..f8607308ea 100644 --- a/native/cocos/renderer/gfx-validator/TextureValidator.cpp +++ b/native/cocos/renderer/gfx-validator/TextureValidator.cpp @@ -28,6 +28,7 @@ #include "DeviceValidator.h" #include "TextureValidator.h" #include "ValidationUtils.h" +#include "gfx-validator/SwapchainValidator.h" namespace cc { namespace gfx { @@ -41,16 +42,16 @@ unordered_map featureCheckMap{ TextureValidator::TextureValidator(Texture *actor) : Agent(actor) { - _typedID = generateObjectID(); + _typedID = actor->getTypedID(); } TextureValidator::~TextureValidator() { DeviceResourceTracker::erase(this); - CC_SAFE_DELETE(_actor); + if (_ownTheActor) CC_SAFE_DELETE(_actor); } void TextureValidator::doInit(const TextureInfo &info) { - CCASSERT(!featureCheckMap.count(_format) || DeviceValidator::getInstance()->hasFeature(featureCheckMap[_format]), "unsupported format"); + CCASSERT(!featureCheckMap.count(_info.format) || DeviceValidator::getInstance()->hasFeature(featureCheckMap[_info.format]), "unsupported format"); // Potentially inefficient static const TextureUsageBit INEFFICIENT_MASK{TextureUsageBit::INPUT_ATTACHMENT | TextureUsageBit::SAMPLED}; @@ -66,11 +67,16 @@ void TextureValidator::doInit(const TextureViewInfo &info) { _actor->initialize(actorInfo); } +void TextureValidator::doInit(const SwapchainTextureInfo &info) { + // the actor is already initialized +} + void TextureValidator::doDestroy() { _actor->destroy(); } void TextureValidator::doResize(uint width, uint height, uint /*size*/) { + CCASSERT(hasFlag(_info.flags, TextureFlagBit::RESIZABLE), "Cannot resize immutable textures"); CCASSERT(!_isTextureView, "Cannot resize texture views"); _actor->resize(width, height); diff --git a/native/cocos/renderer/gfx-validator/TextureValidator.h b/native/cocos/renderer/gfx-validator/TextureValidator.h index f265d23ecc..1b5f9a6ddc 100644 --- a/native/cocos/renderer/gfx-validator/TextureValidator.h +++ b/native/cocos/renderer/gfx-validator/TextureValidator.h @@ -38,13 +38,17 @@ public: void sanityCheck(); + inline void renounceOwnership() { _ownTheActor = false; } + protected: void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; + void doInit(const SwapchainTextureInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; uint _lastUpdateFrame = 0U; + bool _ownTheActor = true; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp index 47955b577d..4181ad9790 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp @@ -64,8 +64,7 @@ void CommandRecorder::recordDrawcall(const DrawcallSnapshot &drawcall) { command.primitive = drawcall.pipelineState->getPrimitive(); command.dynamicStates = drawcall.pipelineState->getDynamicStates(); command.bindPoint = drawcall.pipelineState->getBindPoint(); - - drawcall.inputAssembler->extractDrawInfo(command.drawInfo); + command.drawInfo = drawcall.inputAssembler->getDrawInfo(); command.descriptorSets = drawcall.descriptorSets; for (const auto &offsets : drawcall.dynamicOffsets) command.dynamicOffsets.insert(command.dynamicOffsets.end(), offsets.begin(), offsets.end()); diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.h b/native/cocos/renderer/gfx-validator/ValidationUtils.h index 8e06623b16..0cbe932a31 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.h +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.h @@ -166,7 +166,7 @@ template void DeviceResourceTracker::checkEmpty() { // If this assertion is hit, it means you have leaked gfx resources. // You can debug this by uncomment the `record_stacktrace` template specialization for the relevant type - // and look up the resource initialization stacktrace in `_resources[i].initStack`. + // and look up the resource initialization stacktrace in `resources[i].initStack`. // Note: capturing stacktrace is a painfully time-consuming process, // so better to uncomment the exact type of resource that is leaking rather than toggle them all at once. CCASSERT(resources.empty(), "Resource leaked"); diff --git a/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp index 4f1f3666e0..68def4b867 100644 --- a/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp @@ -33,7 +33,9 @@ namespace cc { namespace gfx { -CCVKBuffer::CCVKBuffer() = default; +CCVKBuffer::CCVKBuffer() { + _typedID = generateObjectID(); +} CCVKBuffer::~CCVKBuffer() { destroy(); @@ -94,8 +96,6 @@ void CCVKBuffer::doDestroy() { } void CCVKBuffer::doResize(uint size, uint count) { - VkDeviceSize oldStartOffset = _gpuBuffer->startOffset; - CCVKDevice::getInstance()->getMemoryStatus().bufferSize -= _size; CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuBuffer); @@ -104,7 +104,7 @@ void CCVKBuffer::doResize(uint size, uint count) { cmdFuncCCVKCreateBuffer(CCVKDevice::getInstance(), _gpuBuffer); _gpuBufferView->range = size; - CCVKDevice::getInstance()->gpuDescriptorHub()->update(_gpuBuffer, oldStartOffset); + CCVKDevice::getInstance()->gpuDescriptorHub()->update(_gpuBuffer); if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { const size_t drawInfoCount = _size / sizeof(DrawInfo); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index fa686de71e..84ba405442 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -28,23 +28,26 @@ #include "VKBuffer.h" #include "VKCommandBuffer.h" #include "VKCommands.h" -#include "VKContext.h" #include "VKDescriptorSet.h" #include "VKDevice.h" #include "VKFramebuffer.h" -#include "VKGlobalBarrier.h" #include "VKInputAssembler.h" #include "VKPipelineState.h" #include "VKQueue.h" #include "VKRenderPass.h" #include "VKTexture.h" -#include "VKTextureBarrier.h" #include "gfx-base/GFXDef-common.h" +#include "states/VKGlobalBarrier.h" +#include "states/VKTextureBarrier.h" #include "vulkan/vulkan_core.h" namespace cc { namespace gfx { +CCVKCommandBuffer::CCVKCommandBuffer() { + _typedID = generateObjectID(); +} + CCVKCommandBuffer::~CCVKCommandBuffer() { destroy(); } @@ -151,7 +154,6 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo if (depthEnabled) { clearValues[attachmentCount].depthStencil = { depth, stencil }; } - auto * device = CCVKDevice::getInstance(); VkRenderPassBeginInfo passBeginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; passBeginInfo.renderPass = gpuRenderPass->vkRenderPass; passBeginInfo.framebuffer = framebuffer; @@ -178,19 +180,11 @@ void CCVKCommandBuffer::endRenderPass() { size_t colorAttachmentCount = _curGPUFBO->gpuRenderPass->colorAttachments.size(); for (size_t i = 0U; i < colorAttachmentCount; ++i) { - if (_curGPUFBO->gpuColorViews[i]) { - _curGPUFBO->gpuColorViews[i]->gpuTexture->currentAccessTypes = _curGPUFBO->gpuRenderPass->endAccesses[i]; - } else { - _curGPUFBO->swapchain->swapchainImageAccessTypes[_curGPUFBO->swapchain->curImageIndex] = _curGPUFBO->gpuRenderPass->endAccesses[i]; - } + _curGPUFBO->gpuColorViews[i]->gpuTexture->currentAccessTypes = _curGPUFBO->gpuRenderPass->endAccesses[i]; } if (_curGPUFBO->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN) { - if (_curGPUFBO->gpuDepthStencilView) { - _curGPUFBO->gpuDepthStencilView->gpuTexture->currentAccessTypes = _curGPUFBO->gpuRenderPass->endAccesses[colorAttachmentCount]; - } else { - _curGPUFBO->swapchain->depthStencilImageAccessTypes[_curGPUFBO->swapchain->curImageIndex] = _curGPUFBO->gpuRenderPass->endAccesses[colorAttachmentCount]; - } + _curGPUFBO->gpuDepthStencilView->gpuTexture->currentAccessTypes = _curGPUFBO->gpuRenderPass->endAccesses[colorAttachmentCount]; } _curGPUFBO = nullptr; @@ -238,17 +232,18 @@ void CCVKCommandBuffer::bindInputAssembler(InputAssembler *ia) { gpuInputAssembler->vertexBufferOffsets.resize(vbCount); } + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); for (uint i = 0U; i < vbCount; ++i) { - gpuInputAssembler->vertexBuffers[i] = gpuInputAssembler->gpuVertexBuffers[i]->vkBuffer; - gpuInputAssembler->vertexBufferOffsets[i] = gpuInputAssembler->gpuVertexBuffers[i]->startOffset; + gpuInputAssembler->vertexBuffers[i] = gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; + gpuInputAssembler->vertexBufferOffsets[i] = gpuInputAssembler->gpuVertexBuffers[i]->getStartOffset(gpuDevice->curBackBufferIndex); } vkCmdBindVertexBuffers(_gpuCommandBuffer->vkCommandBuffer, 0, vbCount, gpuInputAssembler->vertexBuffers.data(), gpuInputAssembler->vertexBufferOffsets.data()); if (gpuInputAssembler->gpuIndexBuffer) { - vkCmdBindIndexBuffer(_gpuCommandBuffer->vkCommandBuffer, gpuInputAssembler->gpuIndexBuffer->vkBuffer, 0, - gpuInputAssembler->gpuIndexBuffer->stride == 4 ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer(_gpuCommandBuffer->vkCommandBuffer, gpuInputAssembler->gpuIndexBuffer->gpuBuffer->vkBuffer, 0, + gpuInputAssembler->gpuIndexBuffer->gpuBuffer->stride == 4 ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_UINT16); } _curGPUInputAssember = gpuInputAssembler; } @@ -364,31 +359,31 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS); } - CCVKGPUBuffer *gpuIndirectBuffer = _curGPUInputAssember->gpuIndirectBuffer; + const auto *gpuIndirectBuffer = _curGPUInputAssember->gpuIndirectBuffer; if (gpuIndirectBuffer) { - uint drawInfoCount = gpuIndirectBuffer->count; + uint drawInfoCount = gpuIndirectBuffer->range / gpuIndirectBuffer->gpuBuffer->stride; CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); - VkDeviceSize offset = gpuIndirectBuffer->startOffset + gpuDevice->curBackBufferIndex * gpuIndirectBuffer->instanceSize; + VkDeviceSize offset = gpuIndirectBuffer->getStartOffset(gpuDevice->curBackBufferIndex); if (gpuDevice->useMultiDrawIndirect) { - if (gpuIndirectBuffer->isDrawIndirectByIndex) { + if (gpuIndirectBuffer->gpuBuffer->isDrawIndirectByIndex) { vkCmdDrawIndexedIndirect(_gpuCommandBuffer->vkCommandBuffer, - gpuIndirectBuffer->vkBuffer, + gpuIndirectBuffer->gpuBuffer->vkBuffer, offset, drawInfoCount, sizeof(VkDrawIndexedIndirectCommand)); } else { vkCmdDrawIndirect(_gpuCommandBuffer->vkCommandBuffer, - gpuIndirectBuffer->vkBuffer, + gpuIndirectBuffer->gpuBuffer->vkBuffer, offset, drawInfoCount, sizeof(VkDrawIndirectCommand)); } } else { - if (gpuIndirectBuffer->isDrawIndirectByIndex) { + if (gpuIndirectBuffer->gpuBuffer->isDrawIndirectByIndex) { for (VkDeviceSize j = 0U; j < drawInfoCount; ++j) { vkCmdDrawIndexedIndirect(_gpuCommandBuffer->vkCommandBuffer, - gpuIndirectBuffer->vkBuffer, + gpuIndirectBuffer->gpuBuffer->vkBuffer, offset + j * sizeof(VkDrawIndexedIndirectCommand), 1, sizeof(VkDrawIndexedIndirectCommand)); @@ -396,7 +391,7 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { } else { for (VkDeviceSize j = 0U; j < drawInfoCount; ++j) { vkCmdDrawIndirect(_gpuCommandBuffer->vkCommandBuffer, - gpuIndirectBuffer->vkBuffer, + gpuIndirectBuffer->gpuBuffer->vkBuffer, offset + j * sizeof(VkDrawIndirectCommand), 1, sizeof(VkDrawIndirectCommand)); @@ -471,24 +466,19 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co VkImage dstImage = VK_NULL_HANDLE; VkImageLayout srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; VkImageLayout dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - CCVKGPUSwapchain * swapchain = CCVKDevice::getInstance()->gpuSwapchain(); - if (srcTexture) { - CCVKGPUTexture *gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); - srcAspectMask = gpuTextureSrc->aspectMask; - srcImage = gpuTextureSrc->vkImage; + CCVKGPUTexture *gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); + srcAspectMask = gpuTextureSrc->aspectMask; + if (gpuTextureSrc->swapchain) { + srcImage = gpuTextureSrc->swapchainVkImages[gpuTextureSrc->swapchain->curImageIndex]; } else { - srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - srcImage = swapchain->swapchainImages[swapchain->curImageIndex]; + srcImage = gpuTextureSrc->vkImage; } - if (dstTexture) { - CCVKGPUTexture *gpuTextureDst = static_cast(dstTexture)->gpuTexture(); - dstAspectMask = gpuTextureDst->aspectMask; - dstImage = gpuTextureDst->vkImage; - } else { - dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - dstImage = swapchain->swapchainImages[swapchain->curImageIndex]; + CCVKGPUTexture *gpuTextureDst = static_cast(dstTexture)->gpuTexture(); + dstAspectMask = gpuTextureDst->aspectMask; + if (gpuTextureDst->swapchain) { + dstImage = gpuTextureDst->swapchainVkImages[gpuTextureDst->swapchain->curImageIndex]; VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; @@ -502,6 +492,8 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &barrier); + } else { + dstImage = gpuTextureDst->vkImage; } _blitRegions.resize(count); @@ -535,12 +527,12 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co dstImage, dstImageLayout, count, _blitRegions.data(), VK_FILTERS[toNumber(filter)]); - if (!dstTexture) { + if (gpuTextureDst->swapchain) { VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = 0; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = dstImage; @@ -548,7 +540,7 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; vkCmdPipelineBarrier(_gpuCommandBuffer->vkCommandBuffer, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_DEPENDENCY_BY_REGION_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &barrier); } } @@ -593,9 +585,10 @@ void CCVKCommandBuffer::dispatch(const DispatchInfo &info) { } if (info.indirectBuffer) { + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); auto *indirectBuffer = static_cast(info.indirectBuffer); vkCmdDispatchIndirect(_gpuCommandBuffer->vkCommandBuffer, indirectBuffer->gpuBuffer()->vkBuffer, - indirectBuffer->gpuBuffer()->startOffset + indirectBuffer->gpuBufferView()->offset + info.indirectOffset); + indirectBuffer->gpuBufferView()->getStartOffset(gpuDevice->curBackBufferIndex) + info.indirectOffset); } else { vkCmdDispatch(_gpuCommandBuffer->vkCommandBuffer, info.groupCountX, info.groupCountY, info.groupCountZ); } @@ -621,23 +614,21 @@ void CCVKCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const Text pImageMemoryBarriers = _imageMemoryBarriers.data(); for (uint i = 0U; i < textureBarrierCount; ++i) { - const auto *gpuBarrier = static_cast(textureBarriers[i])->gpuBarrier(); - _imageMemoryBarriers[i] = gpuBarrier->vkBarrier; + const auto *gpuBarrier = static_cast(textureBarriers[i])->gpuBarrier(); + auto * gpuTexture = static_cast(textures[i])->gpuTexture(); - if (textures[i]) { - auto *gpuTexture = static_cast(textures[i])->gpuTexture(); - _imageMemoryBarriers[i].image = gpuTexture->vkImage; - _imageMemoryBarriers[i].subresourceRange.aspectMask = gpuTexture->aspectMask; - gpuTexture->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount); + _imageMemoryBarriers[i] = gpuBarrier->vkBarrier; + _imageMemoryBarriers[i].subresourceRange.aspectMask = gpuTexture->aspectMask; + if (gpuTexture->swapchain) { + _imageMemoryBarriers[i].image = gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex]; } else { - CCVKGPUSwapchain *swapchain = CCVKDevice::getInstance()->gpuSwapchain(); - _imageMemoryBarriers[i].image = swapchain->swapchainImages[swapchain->curImageIndex]; - _imageMemoryBarriers[i].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - swapchain->swapchainImageAccessTypes[swapchain->curImageIndex].assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount); + _imageMemoryBarriers[i].image = gpuTexture->vkImage; } srcStageMask |= gpuBarrier->srcStageMask; dstStageMask |= gpuBarrier->dstStageMask; + + gpuTexture->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount); } } diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 9b4c0b566d..07be54f84c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -34,7 +34,7 @@ namespace gfx { class CC_VULKAN_API CCVKCommandBuffer final : public CommandBuffer { public: - CCVKCommandBuffer() = default; + CCVKCommandBuffer(); ~CCVKCommandBuffer() override; void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 40b70d1033..17cbe3dbfa 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -25,16 +25,10 @@ #include "VKStd.h" -#include "VKBuffer.h" +#include "gfx-base/SPIRVUtils.h" #include "VKCommands.h" -#include "VKContext.h" #include "VKDevice.h" -#include "VKQueue.h" -#include "VKSPIRV.h" -#include "gfx-base/GFXSampler.h" -#include "vulkan/vulkan_core.h" - -#include +#include "VKGPUObjects.h" namespace cc { namespace gfx { @@ -78,29 +72,27 @@ void insertVkDynamicStates(vector *out, const vectortype) { - case QueueType::GRAPHICS: - queueType = VK_QUEUE_GRAPHICS_BIT; - needPresentable = VK_TRUE; - break; - case QueueType::COMPUTE: queueType = VK_QUEUE_COMPUTE_BIT; break; - case QueueType::TRANSFER: queueType = VK_QUEUE_TRANSFER_BIT; break; - } + if (gpuQueue->possibleQueueFamilyIndices.empty()) { + uint queueType = 0U; + switch (gpuQueue->type) { + case QueueType::GRAPHICS: queueType = VK_QUEUE_GRAPHICS_BIT; break; + case QueueType::COMPUTE: queueType = VK_QUEUE_COMPUTE_BIT; break; + case QueueType::TRANSFER: queueType = VK_QUEUE_TRANSFER_BIT; break; + } - const CCVKGPUContext *context = device->gpuContext(); + const CCVKGPUContext *context = device->gpuContext(); - 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)) { - vkGetDeviceQueue(device->gpuDevice()->vkDevice, i, 0, &gpuQueue->vkQueue); - gpuQueue->queueFamilyIndex = i; - break; + uint queueCount = utils::toUint(context->queueFamilyProperties.size()); + for (uint i = 0U; i < queueCount; ++i) { + const VkQueueFamilyProperties &properties = context->queueFamilyProperties[i]; + if (properties.queueCount > 0 && (properties.queueFlags & queueType)) { + gpuQueue->possibleQueueFamilyIndices.push_back(i); + } } } + + vkGetDeviceQueue(device->gpuDevice()->vkDevice, gpuQueue->possibleQueueFamilyIndices[0], 0, &gpuQueue->vkQueue); + gpuQueue->queueFamilyIndex = gpuQueue->possibleQueueFamilyIndices[0]; } void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { @@ -112,77 +104,104 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { // remove stencil aspect for depth textures with sampled usage if (hasFlag(gpuTexture->usage, TextureUsageBit::SAMPLED)) gpuTexture->aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT; - VkFormat format = mapVkFormat(gpuTexture->format); - VkFormatFeatureFlags features = mapVkFormatFeatureFlags(gpuTexture->usage); - VkFormatProperties formatProperties; - vkGetPhysicalDeviceFormatProperties(device->gpuContext()->physicalDevice, format, &formatProperties); - if (!(formatProperties.optimalTilingFeatures & features)) { - const char *formatName = GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].name.c_str(); - CC_LOG_ERROR("cmdFuncCCVKCreateTexture: The specified usage for %s is not supported on this platform", formatName); - return; - } - - VkImageUsageFlags usageFlags = mapVkImageUsageFlagBits(gpuTexture->usage); - if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { - usageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } - - VkImageCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); - createInfo.imageType = mapVkImageType(gpuTexture->type); - createInfo.format = format; - createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; - createInfo.mipLevels = gpuTexture->mipLevels; - createInfo.arrayLayers = gpuTexture->arrayLayers; - createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, gpuTexture->samples); - createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - createInfo.usage = usageFlags; - createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - VmaAllocationCreateInfo allocInfo{}; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; - - VmaAllocationInfo res; - - 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); - if (!result) { - gpuTexture->memoryless = true; + auto createFn = [device, gpuTexture](VkImage *pVkImage, VmaAllocation *pVmaAllocation) { + VkFormat vkFormat = mapVkFormat(gpuTexture->format, device->gpuDevice()); + VkFormatFeatureFlags features = mapVkFormatFeatureFlags(gpuTexture->usage); + VkFormatProperties formatProperties; + vkGetPhysicalDeviceFormatProperties(device->gpuContext()->physicalDevice, vkFormat, &formatProperties); + if (!(formatProperties.optimalTilingFeatures & features)) { + const char *formatName = GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].name.c_str(); + CC_LOG_ERROR("cmdFuncCCVKCreateTexture: The specified usage for %s is not supported on this platform", formatName); return; } - // feature not present, fallback - createInfo.usage = usageFlags; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; - } + VkImageUsageFlags usageFlags = mapVkImageUsageFlagBits(gpuTexture->usage); + if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { + usageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } - gpuTexture->memoryless = false; - VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, - &gpuTexture->vkImage, &gpuTexture->vmaAllocation, &res)); + VkImageCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); + createInfo.imageType = mapVkImageType(gpuTexture->type); + createInfo.format = vkFormat; + createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; + createInfo.mipLevels = gpuTexture->mipLevels; + createInfo.arrayLayers = gpuTexture->arrayLayers; + createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, vkFormat, gpuTexture->samples); + createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + createInfo.usage = usageFlags; + createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + + VmaAllocationInfo res; + + 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, + pVkImage, pVmaAllocation, &res); + if (!result) { + gpuTexture->memoryless = true; + return; + } + + // feature not present, fallback + createInfo.usage = usageFlags; + allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + } + + gpuTexture->memoryless = false; + VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, + pVkImage, pVmaAllocation, &res)); + }; + + if (gpuTexture->swapchain) { + uint32_t backBufferCount = device->gpuDevice()->backBufferCount; + gpuTexture->swapchainVkImages.resize(backBufferCount); + if (GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].hasDepth) { + gpuTexture->swapchainVmaAllocations.resize(backBufferCount); + for (uint32_t i = 0; i < backBufferCount; ++i) { + createFn(&gpuTexture->swapchainVkImages[i], &gpuTexture->swapchainVmaAllocations[i]); + } + } else { + for (uint32_t i = 0; i < backBufferCount; ++i) { + gpuTexture->swapchainVkImages[i] = gpuTexture->swapchain->swapchainImages[i]; + } + } + gpuTexture->memoryless = true; + } else { + createFn(&gpuTexture->vkImage, &gpuTexture->vmaAllocation); + } } void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTextureView) { - if (!gpuTextureView->gpuTexture || !gpuTextureView->gpuTexture->vkImage) return; + if (!gpuTextureView->gpuTexture) return; - auto formatInfo = GFX_FORMAT_INFOS[toNumber(gpuTextureView->format)]; + auto createFn = [device, gpuTextureView](VkImage vkImage, VkImageView *pVkImageView) { + VkImageViewCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + createInfo.image = vkImage; + createInfo.viewType = mapVkImageViewType(gpuTextureView->type); + createInfo.format = mapVkFormat(gpuTextureView->format, device->gpuDevice()); + createInfo.subresourceRange.aspectMask = gpuTextureView->gpuTexture->aspectMask; + createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; + createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; + createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; + createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; - VkImageAspectFlags aspect = VK_IMAGE_ASPECT_COLOR_BIT; - if (formatInfo.hasDepth) aspect = VK_IMAGE_ASPECT_DEPTH_BIT; + VK_CHECK(vkCreateImageView(device->gpuDevice()->vkDevice, &createInfo, nullptr, pVkImageView)); + }; - 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 = aspect; - createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; - createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; - createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; - createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; - - VK_CHECK(vkCreateImageView(device->gpuDevice()->vkDevice, &createInfo, nullptr, &gpuTextureView->vkImageView)); + if (gpuTextureView->gpuTexture->swapchain) { + uint32_t backBufferCount = device->gpuDevice()->backBufferCount; + gpuTextureView->swapchainVkImageViews.resize(backBufferCount); + for (uint32_t i = 0; i < backBufferCount; ++i) { + createFn(gpuTextureView->gpuTexture->swapchainVkImages[i], &gpuTextureView->swapchainVkImageViews[i]); + } + } else { + createFn(gpuTextureView->gpuTexture->vkImage, &gpuTextureView->vkImageView); + } device->gpuDescriptorHub()->update(gpuTextureView); } @@ -198,14 +217,15 @@ void cmdFuncCCVKCreateSampler(CCVKDevice *device, CCVKGPUSampler *gpuSampler) { createInfo.addressModeU = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressU)]; createInfo.addressModeV = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressV)]; createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressW)]; - createInfo.mipLodBias = gpuSampler->mipLODBias; + createInfo.mipLodBias = 0.F; createInfo.anisotropyEnable = gpuSampler->maxAnisotropy && context->physicalDeviceFeatures.samplerAnisotropy; createInfo.maxAnisotropy = std::min(maxAnisotropy, static_cast(gpuSampler->maxAnisotropy)); createInfo.compareEnable = gpuSampler->cmpFunc != ComparisonFunc::ALWAYS; createInfo.compareOp = VK_CMP_FUNCS[toNumber(gpuSampler->cmpFunc)]; - createInfo.minLod = 0.0; // UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping - createInfo.maxLod = VK_LOD_CLAMP_NONE; // UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping - //createInfo.borderColor; + // From UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping: + // Should use image views with baseMipLevel & levelCount in favor of this + createInfo.minLod = 0.0; + createInfo.maxLod = VK_LOD_CLAMP_NONE; VK_CHECK(vkCreateSampler(device->gpuDevice()->vkDevice, &createInfo, nullptr, &gpuSampler->vkSampler)); } @@ -231,9 +251,9 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; } else if (gpuBuffer->memUsage == (MemoryUsage::HOST | MemoryUsage::DEVICE)) { - //gpuBuffer->instanceSize = roundUp(gpuBuffer->size, device->getCapabilities().uboOffsetAlignment); - //bufferInfo.size = gpuBuffer->instanceSize * device->gpuDevice()->backBufferCount; - //allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + gpuBuffer->instanceSize = roundUp(gpuBuffer->size, device->getCapabilities().uboOffsetAlignment); + bufferInfo.size = gpuBuffer->instanceSize * device->gpuDevice()->backBufferCount; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } @@ -289,14 +309,16 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende thsvsGetAccessInfo(utils::toUint(endAccesses.size()), endAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, attachment.sampleCount); + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, vkFormat, attachment.sampleCount); - attachmentDescriptions[i].format = mapVkFormat(attachment.format); + attachmentDescriptions[i].format = vkFormat; 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; - attachmentDescriptions[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachmentDescriptions[i].stencilLoadOp = hasStencil ? attachmentDescriptions[i].loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[i].stencilStoreOp = hasStencil ? attachmentDescriptions[i].storeOp : VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::LOAD ? beginAccessInfo.imageLayout : VK_IMAGE_LAYOUT_UNDEFINED; attachmentDescriptions[i].finalLayout = endAccessInfo.imageLayout; } @@ -319,14 +341,16 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende thsvsGetAccessInfo(utils::toUint(endAccesses.size()), endAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, depthStencilAttachment.sampleCount); + VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); + bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, vkFormat, depthStencilAttachment.sampleCount); - attachmentDescriptions[colorAttachmentCount].format = mapVkFormat(depthStencilAttachment.format); + attachmentDescriptions[colorAttachmentCount].format = vkFormat; attachmentDescriptions[colorAttachmentCount].samples = samples; attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); - attachmentDescriptions[colorAttachmentCount].stencilLoadOp = mapVkLoadOp(depthStencilAttachment.stencilLoadOp); - attachmentDescriptions[colorAttachmentCount].stencilStoreOp = mapVkStoreOp(depthStencilAttachment.stencilStoreOp); + attachmentDescriptions[colorAttachmentCount].stencilLoadOp = hasStencil ? mapVkLoadOp(depthStencilAttachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[colorAttachmentCount].stencilStoreOp = hasStencil ? mapVkStoreOp(depthStencilAttachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::LOAD ? beginAccessInfo.imageLayout : VK_IMAGE_LAYOUT_UNDEFINED; attachmentDescriptions[colorAttachmentCount].finalLayout = endAccessInfo.imageLayout; } @@ -354,15 +378,17 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, resolve, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } - bool isGeneralLayout{false}; Format dsFormat{Format::UNKNOWN}; if (subpassInfo.depthStencil != INVALID_BINDING) { - if (subpassInfo.depthStencil >= gpuRenderPass->colorAttachments.size()) { + bool isGeneralLayout{false}; + uint attachmentIdx = subpassInfo.depthStencil; + if (subpassInfo.depthStencil >= colorAttachmentCount) { const DepthStencilAttachment & desc = gpuRenderPass->depthStencilAttachment; const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); isGeneralLayout = desc.isGeneralLayout; dsFormat = desc.format; sampleCount = std::max(sampleCount, attachment.samples); + attachmentIdx = utils::toUint(colorAttachmentCount); } else { const ColorAttachment & desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; @@ -375,8 +401,9 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende ? 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}); + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, attachmentIdx, layout, aspect}); } + gpuRenderPass->sampleCounts.push_back(sampleCount); if (subpassInfo.depthStencilResolve != INVALID_BINDING) { @@ -495,7 +522,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende offset += dependency.dstAccesses.size(); } } else { - // explicitly declare external dependencies if not specified + // try to deduce dependencies if not specified // wait for resources to become available by the specified access types VkSubpassDependency2 beginDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, @@ -510,10 +537,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (desc.initialLayout != ref.layout || info.hasWriteAccess || desc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { beginDependency.srcStageMask |= info.stageMask; beginDependency.dstStageMask |= dstStage; - if (desc.initialLayout != ref.layout || info.hasWriteAccess) { - beginDependency.srcAccessMask |= info.hasWriteAccess ? info.accessMask : 0; - beginDependency.dstAccessMask |= (desc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR ? dstAccessWrite : dstAccessRead); - } + beginDependency.srcAccessMask |= info.hasWriteAccess ? info.accessMask : 0; + beginDependency.dstAccessMask |= (desc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR ? dstAccessWrite : dstAccessRead); } }; VkSubpassDescription2 &firstSubpass = subpassDescriptions[0]; @@ -529,7 +554,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende 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) { + if (depthStencilResolves[0].pDepthStencilResolveAttachment) { 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); } @@ -572,6 +597,33 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (endDependency.dstAccessMask) { subpassDependencies.push_back(endDependency); } + + auto findSrcSubpass = [](uint dstSubpass, const VkSubpassDescription2 &target) { + for (uint j = 0; j < dstSubpass; ++j) { + const auto &desc = subpassDescriptions[j]; + for (uint k = 0; k < target.inputAttachmentCount; ++k) { + uint idx = target.pInputAttachments[k].attachment; + for (uint l = 0; l < desc.colorAttachmentCount; ++l) { + if (desc.pColorAttachments[l].attachment == idx) { + return j; + } + } + } + } + return VK_SUBPASS_EXTERNAL; + }; + + // find input attachment dependencies + for (uint i = 0; i < subpassDescriptions.size(); ++i) { + const auto &target = subpassDescriptions[i]; + if (target.inputAttachmentCount) { + subpassDependencies.push_back({VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, + findSrcSubpass(i, target), i, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, + VK_DEPENDENCY_BY_REGION_BIT}); + } + } } VkRenderPassCreateInfo2 renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2}; @@ -588,48 +640,49 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFramebuffer) { size_t colorViewCount = gpuFramebuffer->gpuColorViews.size(); - bool depthSpecified = gpuFramebuffer->gpuDepthStencilView; bool hasDepth = gpuFramebuffer->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN; - vector attachments(colorViewCount + (depthSpecified || hasDepth ? 1 : 0)); - uint swapchainImageIndices = 0; - CCVKGPUTexture * gpuTexture = nullptr; + vector attachments(colorViewCount + hasDepth); + + uint swapchainImageIndices = 0; for (size_t i = 0U; i < colorViewCount; ++i) { CCVKGPUTextureView *texView = gpuFramebuffer->gpuColorViews[i]; - if (texView) { - gpuTexture = gpuFramebuffer->gpuColorViews[i]->gpuTexture; - attachments[i] = gpuFramebuffer->gpuColorViews[i]->vkImageView; - } else { + if (texView->gpuTexture->swapchain) { + gpuFramebuffer->swapchain = texView->gpuTexture->swapchain; swapchainImageIndices |= (1 << i); + } else { + attachments[i] = gpuFramebuffer->gpuColorViews[i]->vkImageView; } } - if (depthSpecified) { - gpuTexture = gpuFramebuffer->gpuDepthStencilView->gpuTexture; - attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->vkImageView; - } else if (hasDepth) { - swapchainImageIndices |= (1 << colorViewCount); + if (hasDepth) { + if (gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain) { + gpuFramebuffer->swapchain = gpuFramebuffer->gpuDepthStencilView->gpuTexture->swapchain; + swapchainImageIndices |= (1 << colorViewCount); + } else { + attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->vkImageView; + } } gpuFramebuffer->isOffscreen = !swapchainImageIndices; if (gpuFramebuffer->isOffscreen) { + CCVKGPUTextureView * gpuTextureView = colorViewCount ? gpuFramebuffer->gpuColorViews[0] : gpuFramebuffer->gpuDepthStencilView; VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; createInfo.attachmentCount = utils::toUint(attachments.size()); createInfo.pAttachments = attachments.data(); - createInfo.width = gpuTexture ? gpuTexture->width : 1; - createInfo.height = gpuTexture ? gpuTexture->height : 1; + createInfo.width = gpuTextureView->gpuTexture->width; + createInfo.height = gpuTextureView->gpuTexture->height; createInfo.layers = 1; VK_CHECK(vkCreateFramebuffer(device->gpuDevice()->vkDevice, &createInfo, nullptr, &gpuFramebuffer->vkFramebuffer)); } else { // swapchain-related framebuffers need special treatments: rebuild is needed // whenever a user-specified attachment or swapchain itself is changed - gpuFramebuffer->swapchain = device->gpuSwapchain(); FramebufferListMap &fboListMap = gpuFramebuffer->swapchain->vkSwapchainFramebufferListMap; auto fboListMapIter = fboListMap.find(gpuFramebuffer); if (fboListMapIter != fboListMap.end() && !fboListMapIter->second.empty()) { return; } - size_t swapchainImageCount = gpuFramebuffer->swapchain->vkSwapchainImageViews.size(); + size_t swapchainImageCount = gpuFramebuffer->swapchain->swapchainImages.size(); if (fboListMapIter != fboListMap.end()) { fboListMapIter->second.resize(swapchainImageCount); } else { @@ -639,19 +692,19 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; createInfo.attachmentCount = utils::toUint(attachments.size()); createInfo.pAttachments = attachments.data(); - createInfo.width = device->getWidth(); - createInfo.height = device->getHeight(); createInfo.layers = 1; for (size_t i = 0U; i < swapchainImageCount; ++i) { for (size_t j = 0U; j < colorViewCount; ++j) { if (swapchainImageIndices & (1 << j)) { - attachments[j] = GFX_FORMAT_INFOS[toNumber(gpuFramebuffer->gpuRenderPass->colorAttachments[j].format)].hasDepth - ? gpuFramebuffer->swapchain->depthStencilImageViews[i] - : gpuFramebuffer->swapchain->vkSwapchainImageViews[i]; + createInfo.width = gpuFramebuffer->gpuColorViews[j]->gpuTexture->width; + createInfo.height = gpuFramebuffer->gpuColorViews[j]->gpuTexture->height; + attachments[j] = gpuFramebuffer->gpuColorViews[j]->swapchainVkImageViews[i]; } } if (swapchainImageIndices & (1 << colorViewCount)) { - attachments[colorViewCount] = gpuFramebuffer->swapchain->depthStencilImageViews[i]; + createInfo.width = gpuFramebuffer->gpuDepthStencilView->gpuTexture->width; + createInfo.height = gpuFramebuffer->gpuDepthStencilView->gpuTexture->height; + attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->swapchainVkImageViews[i]; } VK_CHECK(vkCreateFramebuffer(device->gpuDevice()->vkDevice, &createInfo, nullptr, &fboListMap[gpuFramebuffer][i])); } @@ -659,13 +712,18 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra } void cmdFuncCCVKCreateShader(CCVKDevice *device, CCVKGPUShader *gpuShader) { + SPIRVUtils *spirv = SPIRVUtils::getInstance(); + for (CCVKGPUShaderStage &stage : gpuShader->gpuStages) { - vector spirv = glsl2spirv(stage.type, "#version 450\n" + stage.source, static_cast(device->gpuDevice()->minorVersion)); + spirv->compileGLSL(stage.type, "#version 450\n" + stage.source); + if (stage.type == ShaderStageFlagBit::VERTEX) spirv->compressInputLocations(gpuShader->attributes); + VkShaderModuleCreateInfo createInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - createInfo.codeSize = spirv.size() * sizeof(unsigned int); - createInfo.pCode = spirv.data(); + createInfo.codeSize = spirv->getOutputSize(); + createInfo.pCode = spirv->getOutputData(); VK_CHECK(vkCreateShaderModule(device->gpuDevice()->vkDevice, &createInfo, nullptr, &stage.vkShader)); } + CC_LOG_INFO("Shader '%s' compilation succeeded.", gpuShader->name.c_str()); } @@ -743,7 +801,7 @@ void cmdFuncCCVKCreateComputePipelineState(CCVKDevice *device, CCVKGPUPipelineSt ///////////////////// Shader Stage ///////////////////// - const CCVKGPUShaderStageList & stages = gpuPipelineState->gpuShader->gpuStages; + const auto & stages = gpuPipelineState->gpuShader->gpuStages; VkPipelineShaderStageCreateInfo stageInfo{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; stageInfo.stage = mapVkShaderStageFlagBits(stages[0].type); stageInfo.module = stages[0].vkShader; @@ -770,8 +828,8 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ///////////////////// Shader Stage ///////////////////// - const CCVKGPUShaderStageList &stages = gpuPipelineState->gpuShader->gpuStages; - const size_t stageCount = stages.size(); + const auto & 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) { @@ -817,7 +875,7 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS if (shaderAttrs[i].name == attr.name) { attributeDescriptions[i].location = shaderAttrs[i].location; attributeDescriptions[i].binding = attr.stream; - attributeDescriptions[i].format = mapVkFormat(attr.format); + attributeDescriptions[i].format = mapVkFormat(attr.format, device->gpuDevice()); attributeDescriptions[i].offset = offsets[attr.stream]; attributeFound = true; break; @@ -827,7 +885,7 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS if (!attributeFound) { // handle absent attribute attributeDescriptions[i].location = shaderAttrs[i].location; attributeDescriptions[i].binding = 0; - attributeDescriptions[i].format = mapVkFormat(shaderAttrs[i].format); + attributeDescriptions[i].format = mapVkFormat(shaderAttrs[i].format, device->gpuDevice()); attributeDescriptions[i].offset = 0; // reuse the first attribute as dummy data } } @@ -1022,7 +1080,7 @@ void cmdFuncCCVKUpdateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer, const VkBufferCopy region{ stagingBuffer.startOffset, - gpuBuffer->startOffset + backBufferIndex * gpuBuffer->instanceSize, + gpuBuffer->getStartOffset(backBufferIndex), sizeToUpload, }; auto upload = [&stagingBuffer, &gpuBuffer, ®ion](const CCVKGPUCommandBuffer *gpuCommandBuffer) { @@ -1116,7 +1174,7 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { VkFormatProperties formatProperties; - vkGetPhysicalDeviceFormatProperties(device->gpuContext()->physicalDevice, mapVkFormat(gpuTexture->format), &formatProperties); + vkGetPhysicalDeviceFormatProperties(device->gpuContext()->physicalDevice, mapVkFormat(gpuTexture->format, device->gpuDevice()), &formatProperties); VkFormatFeatureFlags mipmapFeatures = VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; if (formatProperties.optimalTilingFeatures & mipmapFeatures) { @@ -1167,9 +1225,7 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b device->gpuBarrierManager()->checkIn(gpuTexture); } -CC_VULKAN_API void cmdFuncCCVKCopyTextureToBuffers(CCVKDevice *device, CCVKGPUTexture *srcTexture, CCVKGPUBuffer *destBuffer, const BufferTextureCopy *regions, uint count, const CCVKGPUCommandBuffer *gpuCommandBuffer) { - (void)device; // fix clang-tidy error - +CC_VULKAN_API void cmdFuncCCVKCopyTextureToBuffers(CCVKDevice * /*device*/, CCVKGPUTexture *srcTexture, CCVKGPUBuffer *destBuffer, const BufferTextureCopy *regions, uint count, const CCVKGPUCommandBuffer *gpuCommandBuffer) { ThsvsImageBarrier barrier{}; barrier.image = srcTexture->vkImage; barrier.discardContents = false; @@ -1245,7 +1301,7 @@ void cmdFuncCCVKDestroyFramebuffer(CCVKGPUDevice *gpuDevice, CCVKGPUFramebuffer vkDestroyFramebuffer(gpuDevice->vkDevice, gpuFramebuffer->vkFramebuffer, nullptr); gpuFramebuffer->vkFramebuffer = VK_NULL_HANDLE; } - } else { + } else if (gpuDevice->swapchains.count(gpuFramebuffer->swapchain)) { FramebufferListMap &fboListMap = gpuFramebuffer->swapchain->vkSwapchainFramebufferListMap; auto fboListMapIter = fboListMap.find(gpuFramebuffer); if (fboListMapIter != fboListMap.end()) { @@ -1385,8 +1441,8 @@ void CCVKGPURecycleBin::clear() { _count = 0; } -VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format, SampleCount sampleCount) const { - if (sampleCount <= SampleCount::X1) return VK_SAMPLE_COUNT_1_BIT; +VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const { + if (sampleCount <= SampleCount::ONE) return VK_SAMPLE_COUNT_1_BIT; static unordered_map cacheMap; if (!cacheMap.count(format)) { @@ -1394,20 +1450,20 @@ VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format 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, + vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usages, 0, &properties); cacheMap[format] = properties.sampleCounts; } VkSampleCountFlags availableSampleCounts = cacheMap[format]; - auto requestedSampleCount = toNumber(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; + auto requestedSampleCount = VK_SAMPLE_COUNT_FLAGS[toNumber(sampleCount)]; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_64_BIT) return VK_SAMPLE_COUNT_64_BIT; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_32_BIT) return VK_SAMPLE_COUNT_32_BIT; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_16_BIT) return VK_SAMPLE_COUNT_16_BIT; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT; + if (requestedSampleCount & availableSampleCounts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT; return VK_SAMPLE_COUNT_1_BIT; } @@ -1513,8 +1569,8 @@ void CCVKGPUBufferHub::flush(CCVKGPUTransportHub *transportHub) { VkBufferCopy region; for (auto &buffer : buffers) { if (buffer.second.canMemcpy) continue; - region.srcOffset = buffer.first->startOffset + buffer.second.srcIndex * buffer.first->instanceSize; - region.dstOffset = buffer.first->startOffset + _device->curBackBufferIndex * buffer.first->instanceSize; + region.srcOffset = buffer.first->getStartOffset(buffer.second.srcIndex); + region.dstOffset = buffer.first->getStartOffset(_device->curBackBufferIndex); region.size = buffer.second.size; vkCmdCopyBuffer(gpuCommandBuffer->vkCommandBuffer, buffer.first->vkBuffer, buffer.first->vkBuffer, 1, ®ion); } diff --git a/native/cocos/renderer/gfx-vulkan/VKContext.cpp b/native/cocos/renderer/gfx-vulkan/VKContext.cpp deleted file mode 100644 index a83f12340d..0000000000 --- a/native/cocos/renderer/gfx-vulkan/VKContext.cpp +++ /dev/null @@ -1,566 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "VKStd.h" - -#include "VKContext.h" -#include "VKDevice.h" -#include "VKGPUObjects.h" -#include "VKQueue.h" -#include "VKRenderPass.h" -#include "VKTexture.h" - -#include "VKUtils.h" - -namespace cc { -namespace gfx { - -namespace { - -constexpr uint FORCE_MINOR_VERSION = 0; // 0 for default version, otherwise minorVersion = (FORCE_MINOR_VERSION - 1) -constexpr uint DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled - -#define FORCE_ENABLE_VALIDATION 0 -#define FORCE_DISABLE_VALIDATION 1 - -#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION -VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageType, - const VkDebugUtilsMessengerCallbackDataEXT *callbackData, - void * userData) { - if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { - CC_LOG_ERROR("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); - CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); - return VK_FALSE; - } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { - CC_LOG_WARNING("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); - return VK_FALSE; - } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { - //CC_LOG_INFO("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); - return VK_FALSE; - } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) { - //CC_LOG_DEBUG("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); - return VK_FALSE; - } - CC_LOG_ERROR("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); - return VK_FALSE; -} - -VKAPI_ATTR VkBool32 VKAPI_CALL debugReportCallback(VkDebugReportFlagsEXT flags, - VkDebugReportObjectTypeEXT type, - uint64_t object, - size_t location, - int32_t messageCode, - const char * layerPrefix, - const char * message, - void * userData) { - if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { - CC_LOG_ERROR("%s: %s", layerPrefix, message); - CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); - return VK_FALSE; - } else if (flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)) { - CC_LOG_WARNING("%s: %s", layerPrefix, message); - return VK_FALSE; - } else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { - //CC_LOG_INFO("%s: %s", layerPrefix, message); - return VK_FALSE; - } else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { - //CC_LOG_DEBUG("%s: %s", layerPrefix, message); - return VK_FALSE; - } - CC_LOG_ERROR("%s: %s", layerPrefix, message); - return VK_FALSE; -} -#endif -} // namespace - -bool CCVKContext::doInit(const ContextInfo &info) { - if (!info.sharedCtx) { - _isPrimaryContex = true; - - _gpuContext = CC_NEW(CCVKGPUContext); - - // only enable the absolute essentials for now - vector requestedLayers{ - - }; - vector requestedExtensions{ - VK_KHR_SURFACE_EXTENSION_NAME, - }; - - ///////////////////// Instance Creation ///////////////////// - - if (volkInitialize()) { - return false; - } - - uint apiVersion = VK_API_VERSION_1_0; - if (vkEnumerateInstanceVersion) { - vkEnumerateInstanceVersion(&apiVersion); - if (FORCE_MINOR_VERSION) { - apiVersion = VK_MAKE_VERSION(1, FORCE_MINOR_VERSION - 1, 0); - } - } - - uint minorVersion = VK_VERSION_MINOR(apiVersion); - if (minorVersion < 1) { - requestedExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); - } - - uint availableLayerCount; - VK_CHECK(vkEnumerateInstanceLayerProperties(&availableLayerCount, nullptr)); - vector supportedLayers(availableLayerCount); - VK_CHECK(vkEnumerateInstanceLayerProperties(&availableLayerCount, supportedLayers.data())); - - uint availableExtensionCount; - VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &availableExtensionCount, nullptr)); - vector supportedExtensions(availableExtensionCount); - VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &availableExtensionCount, supportedExtensions.data())); - -#if defined(VK_USE_PLATFORM_ANDROID_KHR) - requestedExtensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME); -#elif defined(VK_USE_PLATFORM_WIN32_KHR) - requestedExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); -#elif defined(VK_USE_PLATFORM_METAL_EXT) - requestedExtensions.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME); -#elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - requestedExtensions.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME); -#elif defined(VK_USE_PLATFORM_XCB_KHR) - requestedExtensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME); -#else - #pragma error Platform not supported -#endif - -#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION - // Determine the optimal validation layers to enable that are necessary for useful debugging - vector> validationLayerPriorityList{ - // The preferred validation layer is "VK_LAYER_KHRONOS_validation" - {"VK_LAYER_KHRONOS_validation"}, - - // Otherwise we fallback to using the LunarG meta layer - {"VK_LAYER_LUNARG_standard_validation"}, - - // Otherwise we attempt to enable the individual layers that compose the LunarG meta layer since it doesn't exist - { - "VK_LAYER_GOOGLE_threading", - "VK_LAYER_LUNARG_parameter_validation", - "VK_LAYER_LUNARG_object_tracker", - "VK_LAYER_LUNARG_core_validation", - "VK_LAYER_GOOGLE_unique_objects", - }, - - // Otherwise as a last resort we fallback to attempting to enable the LunarG core layer - {"VK_LAYER_LUNARG_core_validation"}, - }; - for (vector &validationLayers : validationLayerPriorityList) { - bool found = true; - for (const char *layer : validationLayers) { - if (!isLayerSupported(layer, supportedLayers)) { - found = false; - break; - } - } - if (found) { - requestedLayers.insert(requestedLayers.end(), validationLayers.begin(), validationLayers.end()); - break; - } - } - - // Check if VK_EXT_debug_utils is supported, which supersedes VK_EXT_Debug_Report - bool debugUtils = false; - if (isExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, supportedExtensions)) { - debugUtils = true; - requestedExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); - } else { - requestedExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); - } -#endif - - // just filter out the unsupported layers & extensions - for (const char *layer : requestedLayers) { - if (isLayerSupported(layer, supportedLayers)) { - _layers.push_back(layer); - } - } - for (const char *extension : requestedExtensions) { - if (isExtensionSupported(extension, supportedExtensions)) { - _extensions.push_back(extension); - } - } - - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.pEngineName = "Cocos Creator"; - app.apiVersion = apiVersion; - - VkInstanceCreateInfo instanceInfo{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - instanceInfo.pApplicationInfo = &app; - instanceInfo.enabledExtensionCount = utils::toUint(_extensions.size()); - instanceInfo.ppEnabledExtensionNames = _extensions.data(); - instanceInfo.enabledLayerCount = utils::toUint(_layers.size()); - instanceInfo.ppEnabledLayerNames = _layers.data(); - -#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION - VkDebugUtilsMessengerCreateInfoEXT debugUtilsCreateInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - VkDebugReportCallbackCreateInfoEXT debugReportCreateInfo{VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT}; - if (debugUtils) { - debugUtilsCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT; - debugUtilsCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; - debugUtilsCreateInfo.pfnUserCallback = debugUtilsMessengerCallback; - - instanceInfo.pNext = &debugUtilsCreateInfo; - } else { - debugReportCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | - VK_DEBUG_REPORT_WARNING_BIT_EXT | - VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | - VK_DEBUG_REPORT_INFORMATION_BIT_EXT | - VK_DEBUG_REPORT_DEBUG_BIT_EXT; - debugReportCreateInfo.pfnCallback = debugReportCallback; - - instanceInfo.pNext = &debugReportCreateInfo; - } -#endif - - // Create the Vulkan instance - VkResult res = vkCreateInstance(&instanceInfo, nullptr, &_gpuContext->vkInstance); - if (res == VK_ERROR_LAYER_NOT_PRESENT) { - CC_LOG_ERROR("Create Vulkan instance failed due to missing layers, aborting..."); - return false; - } - - volkLoadInstanceOnly(_gpuContext->vkInstance); - -#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION - if (debugUtils) { - VK_CHECK(vkCreateDebugUtilsMessengerEXT(_gpuContext->vkInstance, &debugUtilsCreateInfo, nullptr, &_gpuContext->vkDebugUtilsMessenger)); - } else { - VK_CHECK(vkCreateDebugReportCallbackEXT(_gpuContext->vkInstance, &debugReportCreateInfo, nullptr, &_gpuContext->vkDebugReport)); - } - _validationEnabled = true; -#endif - - ///////////////////// Surface Creation ///////////////////// - -#if defined(VK_USE_PLATFORM_ANDROID_KHR) - VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR}; - surfaceCreateInfo.window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - VK_CHECK(vkCreateAndroidSurfaceKHR(_gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuContext->vkSurface)); -#elif defined(VK_USE_PLATFORM_WIN32_KHR) - VkWin32SurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - surfaceCreateInfo.hinstance = static_cast(GetModuleHandle(0)); - surfaceCreateInfo.hwnd = reinterpret_cast(_windowHandle); - VK_CHECK(vkCreateWin32SurfaceKHR(_gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuContext->vkSurface)); -#elif defined(VK_USE_PLATFORM_METAL_EXT) - VkMetalSurfaceCreateInfoEXT surfaceCreateInfo{VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT}; - surfaceCreateInfo.pLayer = reinterpret_cast(_windowHandle); - VK_CHECK(vkCreateMetalSurfaceEXT(_gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuContext->vkSurface)); -#elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - VkWaylandSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR}; - surfaceCreateInfo.display = nullptr; // TODO - surfaceCreateInfo.surface = reinterpret_cast(_windowHandle); - VK_CHECK(vkCreateWaylandSurfaceKHR(_gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuContext->vkSurface)); -#elif defined(VK_USE_PLATFORM_XCB_KHR) - VkXcbSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR}; - surfaceCreateInfo.connection = nullptr; // TODO - surfaceCreateInfo.window = static_cast(_windowHandle); - VK_CHECK(vkCreateXcbSurfaceKHR(_gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuContext->vkSurface)); -#else - #pragma error Platform not supported -#endif - - ///////////////////// Physical Device Selection ///////////////////// - - // Querying valid physical devices on the machine - uint physicalDeviceCount{0}; - res = vkEnumeratePhysicalDevices(_gpuContext->vkInstance, &physicalDeviceCount, nullptr); - - if (res || physicalDeviceCount < 1) { - return false; - } - - vector physicalDeviceHandles(physicalDeviceCount); - VK_CHECK(vkEnumeratePhysicalDevices(_gpuContext->vkInstance, &physicalDeviceCount, physicalDeviceHandles.data())); - - vector physicalDeviceProperties(physicalDeviceCount); - - uint deviceIndex; - for (deviceIndex = 0U; deviceIndex < physicalDeviceCount; ++deviceIndex) { - VkPhysicalDeviceProperties &properties = physicalDeviceProperties[deviceIndex]; - vkGetPhysicalDeviceProperties(physicalDeviceHandles[deviceIndex], &properties); - } - - for (deviceIndex = 0U; deviceIndex < physicalDeviceCount; ++deviceIndex) { - VkPhysicalDeviceProperties &properties = physicalDeviceProperties[deviceIndex]; - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { - break; - } - } - - if (deviceIndex == physicalDeviceCount) { - deviceIndex = 0; - } - - _gpuContext->physicalDevice = physicalDeviceHandles[deviceIndex]; - _gpuContext->physicalDeviceProperties = physicalDeviceProperties[deviceIndex]; - vkGetPhysicalDeviceFeatures(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceFeatures); - - _majorVersion = VK_VERSION_MAJOR(_gpuContext->physicalDeviceProperties.apiVersion); - _minorVersion = VK_VERSION_MINOR(_gpuContext->physicalDeviceProperties.apiVersion); - - 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); - } else { - vkGetPhysicalDeviceProperties2KHR(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceProperties2); - vkGetPhysicalDeviceFeatures2KHR(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceFeatures2); - } - } - - vkGetPhysicalDeviceMemoryProperties(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceMemoryProperties); - uint queueFamilyPropertiesCount = 0; - vkGetPhysicalDeviceQueueFamilyProperties(_gpuContext->physicalDevice, &queueFamilyPropertiesCount, nullptr); - _gpuContext->queueFamilyProperties.resize(queueFamilyPropertiesCount); - vkGetPhysicalDeviceQueueFamilyProperties(_gpuContext->physicalDevice, &queueFamilyPropertiesCount, _gpuContext->queueFamilyProperties.data()); - _gpuContext->queueFamilyPresentables.resize(queueFamilyPropertiesCount); - for (uint propertyIndex = 0U; propertyIndex < queueFamilyPropertiesCount; propertyIndex++) { - vkGetPhysicalDeviceSurfaceSupportKHR(_gpuContext->physicalDevice, propertyIndex, - _gpuContext->vkSurface, &_gpuContext->queueFamilyPresentables[propertyIndex]); - } - - ///////////////////// Swapchain Preparation ///////////////////// - - _colorFmt = Format::BGRA8; - _depthStencilFmt = Format::D24S8; - - VkSurfaceCapabilitiesKHR surfaceCapabilities{}; - vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_gpuContext->physicalDevice, _gpuContext->vkSurface, &surfaceCapabilities); - - uint surfaceFormatCount = 0U; - VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(_gpuContext->physicalDevice, _gpuContext->vkSurface, &surfaceFormatCount, nullptr)); - vector surfaceFormats(surfaceFormatCount); - VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(_gpuContext->physicalDevice, _gpuContext->vkSurface, &surfaceFormatCount, surfaceFormats.data())); - - uint presentModeCount = 0U; - VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(_gpuContext->physicalDevice, _gpuContext->vkSurface, &presentModeCount, nullptr)); - vector presentModes(presentModeCount); - VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(_gpuContext->physicalDevice, _gpuContext->vkSurface, &presentModeCount, presentModes.data())); - - VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; - // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, - // there is no preferred format, so we assume VK_FORMAT_B8G8R8A8_UNORM - if ((surfaceFormatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { - colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - colorSpace = surfaceFormats[0].colorSpace; - } else { - // iterate over the list of available surface format and - // check for the presence of VK_FORMAT_B8G8R8A8_UNORM - bool imageFormatFound = false; - for (VkSurfaceFormatKHR &surfaceFormat : surfaceFormats) { - if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { - colorFormat = surfaceFormat.format; - colorSpace = surfaceFormat.colorSpace; - imageFormatFound = true; - break; - } - } - - // in case VK_FORMAT_B8G8R8A8_UNORM is not available - // select the first available color format - if (!imageFormatFound) { - colorFormat = surfaceFormats[0].format; - colorSpace = surfaceFormats[0].colorSpace; - switch (colorFormat) { - case VK_FORMAT_R8G8B8A8_UNORM: _colorFmt = Format::RGBA8; break; - case VK_FORMAT_R8G8B8A8_SRGB: _colorFmt = Format::SRGB8_A8; break; - case VK_FORMAT_R5G6B5_UNORM_PACK16: _colorFmt = Format::R5G6B5; break; - default: CCASSERT(0, "assumption broken: new default surface format"); break; - } - } - } - - vector> depthFormatPriorityList = { - {Format::D24S8, VK_FORMAT_D24_UNORM_S8_UINT}, - {Format::D32F_S8, VK_FORMAT_D32_SFLOAT_S8_UINT}, - {Format::D16S8, VK_FORMAT_D16_UNORM_S8_UINT}, - {Format::D32F, VK_FORMAT_D32_SFLOAT}, - {Format::D16, VK_FORMAT_D16_UNORM}, - }; - for (std::pair &format : depthFormatPriorityList) { - VkFormatProperties formatProperties; - vkGetPhysicalDeviceFormatProperties(_gpuContext->physicalDevice, format.second, &formatProperties); - // Format must support depth stencil attachment for optimal tiling - if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { - if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { - _depthStencilFmt = format.first; - break; - } - } - } - - // Select a present mode for the swapchain - - vector presentModePriorityList; - - switch (_vsyncMode) { - case VsyncMode::OFF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::ON: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::RELAXED: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_RELAXED_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::MAILBOX: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::HALF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; // no easy fallback - } - - VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; - - for (VkPresentModeKHR presentMode : presentModePriorityList) { - if (std::find(presentModes.begin(), presentModes.end(), presentMode) != presentModes.end()) { - swapchainPresentMode = presentMode; - } - } - - // Determine the number of images - uint desiredNumberOfSwapchainImages = std::max(3U, surfaceCapabilities.minImageCount + 1); - - if ((surfaceCapabilities.maxImageCount > 0) && (desiredNumberOfSwapchainImages > surfaceCapabilities.maxImageCount)) { - desiredNumberOfSwapchainImages = surfaceCapabilities.maxImageCount; - } - - VkExtent2D imageExtent = {1U, 1U}; - VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; - - // Find a supported composite alpha format (not all devices support alpha opaque) - VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - // Simply select the first composite alpha format available - vector compositeAlphaFlags = { - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, - }; - for (VkCompositeAlphaFlagBitsKHR compositeAlphaFlag : compositeAlphaFlags) { - if (surfaceCapabilities.supportedCompositeAlpha & compositeAlphaFlag) { - compositeAlpha = compositeAlphaFlag; - break; - }; - } - VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - // Enable transfer source on swap chain images if supported - if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { - imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } - - // Enable transfer destination on swap chain images if supported - if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) { - imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; - } - - _gpuContext->swapchainCreateInfo.surface = _gpuContext->vkSurface; - _gpuContext->swapchainCreateInfo.minImageCount = desiredNumberOfSwapchainImages; - _gpuContext->swapchainCreateInfo.imageFormat = colorFormat; - _gpuContext->swapchainCreateInfo.imageColorSpace = colorSpace; - _gpuContext->swapchainCreateInfo.imageExtent = imageExtent; - _gpuContext->swapchainCreateInfo.imageUsage = imageUsage; - _gpuContext->swapchainCreateInfo.imageArrayLayers = 1; - _gpuContext->swapchainCreateInfo.preTransform = preTransform; - _gpuContext->swapchainCreateInfo.compositeAlpha = compositeAlpha; - _gpuContext->swapchainCreateInfo.presentMode = swapchainPresentMode; - _gpuContext->swapchainCreateInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area - - } else { - auto *sharedCtx = static_cast(info.sharedCtx); - _majorVersion = sharedCtx->majorVersion(); - _minorVersion = sharedCtx->minorVersion(); - _layers = sharedCtx->getLayers(); - _extensions = sharedCtx->getExtensions(); - _gpuContext = sharedCtx->gpuContext(); - } - - return true; -} - -void CCVKContext::doDestroy() { - if (_gpuContext) { - if (_gpuContext->vkSurface != VK_NULL_HANDLE) { - vkDestroySurfaceKHR(_gpuContext->vkInstance, _gpuContext->vkSurface, nullptr); - _gpuContext->vkSurface = VK_NULL_HANDLE; - } - -#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION - if (_gpuContext->vkDebugUtilsMessenger != VK_NULL_HANDLE) { - vkDestroyDebugUtilsMessengerEXT(_gpuContext->vkInstance, _gpuContext->vkDebugUtilsMessenger, nullptr); - _gpuContext->vkDebugUtilsMessenger = VK_NULL_HANDLE; - } - if (_gpuContext->vkDebugReport != VK_NULL_HANDLE) { - vkDestroyDebugReportCallbackEXT(_gpuContext->vkInstance, _gpuContext->vkDebugReport, nullptr); - _gpuContext->vkDebugReport = VK_NULL_HANDLE; - } -#endif - - if (_gpuContext->vkInstance != VK_NULL_HANDLE) { - vkDestroyInstance(_gpuContext->vkInstance, nullptr); - _gpuContext->vkInstance = VK_NULL_HANDLE; - } - - CC_DELETE(_gpuContext); - _gpuContext = nullptr; - } -} - -void CCVKContext::releaseSurface(uintptr_t /*windowHandle*/) { -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) - if (_gpuContext && _gpuContext->vkSurface == VK_NULL_HANDLE) return; - - CCVKDevice *device = CCVKDevice::getInstance(); - device->waitAllFences(); - device->destroySwapchain(); - device->_swapchainReady = false; - - vkDestroySurfaceKHR(_gpuContext->vkInstance, _gpuContext->vkSurface, nullptr); - _gpuContext->vkSurface = VK_NULL_HANDLE; -#endif -} - -void CCVKContext::acquireSurface(uintptr_t windowHandle) { -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) - _windowHandle = windowHandle; - if (_gpuContext && _gpuContext->vkSurface != VK_NULL_HANDLE) return; - - VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR}; - surfaceCreateInfo.window = reinterpret_cast(_windowHandle); // NOLINT(performance-no-int-to-ptr) - VK_CHECK(vkCreateAndroidSurfaceKHR(_gpuContext->vkInstance, &surfaceCreateInfo, - nullptr, &_gpuContext->vkSurface)); - - CCVKDevice::getInstance()->checkSwapchainStatus(); -#endif -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKContext.h b/native/cocos/renderer/gfx-vulkan/VKContext.h deleted file mode 100644 index 4efadab9e0..0000000000 --- a/native/cocos/renderer/gfx-vulkan/VKContext.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "VKStd.h" -#include "gfx-base/GFXContext.h" - -namespace cc { -namespace gfx { - -class CCVKDevice; -class CCVKGPUDevice; -class CCVKGPUContext; -class CCVKGPUSwapchain; -class CCVKGPUSemaphorePool; - -class CC_VULKAN_API CCVKContext final : public Context { -public: - CCVKContext() = default; - ~CCVKContext() override = default; - - void present() override {} - - inline bool checkExtension(const String &extension) const { - return std::any_of(_extensions.begin(), _extensions.end(), [&extension](auto &ext) { - return std::strcmp(ext, extension.c_str()) == 0; - }); - } - - inline int majorVersion() const { return _majorVersion; } - inline int minorVersion() const { return _minorVersion; } - inline CCVKGPUContext * gpuContext() { return _gpuContext; } - inline const vector &getLayers() const { return _layers; } - inline const vector &getExtensions() const { return _extensions; } - - inline bool validationEnabled() const { return _validationEnabled; } - - void releaseSurface(uintptr_t windowHandle); - void acquireSurface(uintptr_t windowHandle); - -protected: - bool doInit(const ContextInfo &info) override; - void doDestroy() override; - - CCVKGPUContext * _gpuContext = nullptr; - bool _isPrimaryContex = false; - int _majorVersion = 0; - int _minorVersion = 0; - vector _layers; - vector _extensions; - - bool _validationEnabled = false; -}; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp index e019f8f7f6..ee8911541f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp @@ -31,14 +31,16 @@ #include "VKDescriptorSetLayout.h" #include "VKDevice.h" #include "VKPipelineLayout.h" -#include "VKSampler.h" #include "VKShader.h" #include "VKTexture.h" +#include "states/VKSampler.h" namespace cc { namespace gfx { -CCVKDescriptorSet::CCVKDescriptorSet() = default; +CCVKDescriptorSet::CCVKDescriptorSet() { + _typedID = generateObjectID(); +} CCVKDescriptorSet::~CCVKDescriptorSet() { destroy(); @@ -103,7 +105,7 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { for (uint j = 0; j < binding.count; ++j, ++k) { if (hasFlag(DESCRIPTOR_BUFFER_TYPE, binding.descriptorType)) { instance.descriptorInfos[k].buffer.buffer = gpuDevice->defaultBuffer.vkBuffer; - instance.descriptorInfos[k].buffer.offset = gpuDevice->defaultBuffer.startOffset; + instance.descriptorInfos[k].buffer.offset = gpuDevice->defaultBuffer.getStartOffset(t); instance.descriptorInfos[k].buffer.range = gpuDevice->defaultBuffer.size; } else if (hasFlag(DESCRIPTOR_TEXTURE_TYPE, binding.descriptorType)) { instance.descriptorInfos[k].image.sampler = gpuDevice->defaultSampler.vkSampler; diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp index e5a7271f96..759cefd917 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp @@ -34,7 +34,9 @@ namespace cc { namespace gfx { -CCVKDescriptorSetLayout::CCVKDescriptorSetLayout() = default; +CCVKDescriptorSetLayout::CCVKDescriptorSetLayout() { + _typedID = generateObjectID(); +} CCVKDescriptorSetLayout::~CCVKDescriptorSetLayout() { destroy(); diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index dffd16ed4d..faab9c14f6 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -27,22 +27,23 @@ #include "VKBuffer.h" #include "VKCommandBuffer.h" -#include "VKContext.h" #include "VKDescriptorSet.h" #include "VKDescriptorSetLayout.h" #include "VKDevice.h" #include "VKFramebuffer.h" -#include "VKGlobalBarrier.h" #include "VKInputAssembler.h" #include "VKPipelineLayout.h" #include "VKPipelineState.h" #include "VKQueue.h" #include "VKRenderPass.h" -#include "VKSampler.h" #include "VKShader.h" +#include "VKSwapchain.h" #include "VKTexture.h" -#include "VKTextureBarrier.h" #include "VKUtils.h" +#include "gfx-base/SPIRVUtils.h" +#include "states/VKGlobalBarrier.h" +#include "states/VKSampler.h" +#include "states/VKTextureBarrier.h" CC_DISABLE_WARNINGS() #define VMA_IMPLEMENTATION @@ -57,8 +58,6 @@ CC_ENABLE_WARNINGS() namespace cc { namespace gfx { -//#define DISABLE_PRE_TRANSFORM - static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, @@ -85,35 +84,24 @@ CCVKDevice::~CCVKDevice() { CCVKDevice::instance = nullptr; } -CCVKGPUContext *CCVKDevice::gpuContext() const { - return static_cast(_context)->gpuContext(); -} - -bool CCVKDevice::doInit(const DeviceInfo &info) { - ContextInfo ctxInfo; - ctxInfo.windowHandle = _windowHandle; - ctxInfo.msaaEnabled = info.isAntiAlias; - ctxInfo.performance = Performance::HIGH_QUALITY; - - _context = CC_NEW(CCVKContext); - if (!_context->initialize(ctxInfo)) { +bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { + _gpuContext = CC_NEW(CCVKGPUContext); + if (!_gpuContext->initialize()) { destroy(); return false; } - auto * context = static_cast(_context); - const CCVKGPUContext * gpuContext = context->gpuContext(); - const VkPhysicalDeviceFeatures2 &deviceFeatures2 = gpuContext->physicalDeviceFeatures2; + const VkPhysicalDeviceFeatures2 &deviceFeatures2 = _gpuContext->physicalDeviceFeatures2; const VkPhysicalDeviceFeatures & deviceFeatures = deviceFeatures2.features; - //const VkPhysicalDeviceVulkan11Features &deviceVulkan11Features = gpuContext->physicalDeviceVulkan11Features; - //const VkPhysicalDeviceVulkan12Features &deviceVulkan12Features = gpuContext->physicalDeviceVulkan12Features; + //const VkPhysicalDeviceVulkan11Features &deviceVulkan11Features = _gpuContext->physicalDeviceVulkan11Features; + //const VkPhysicalDeviceVulkan12Features &deviceVulkan12Features = _gpuContext->physicalDeviceVulkan12Features; ///////////////////// Device Creation ///////////////////// _gpuDevice = CC_NEW(CCVKGPUDevice); - _gpuDevice->minorVersion = context->minorVersion(); + _gpuDevice->minorVersion = _gpuContext->minorVersion; - // only enable the absolute essentials for now + // only enable the absolute essentials vector requestedLayers{}; vector requestedExtensions{ VK_KHR_SWAPCHAIN_EXTENSION_NAME, @@ -138,25 +126,20 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { requestedFeatures2.features.depthBounds = deviceFeatures.depthBounds; requestedFeatures2.features.multiDrawIndirect = deviceFeatures.multiDrawIndirect; - if (context->validationEnabled()) { + if (_gpuContext->validationEnabled) { requestedLayers.push_back("VK_LAYER_KHRONOS_validation"); - // GPU-assisted validation - requestedFeatures2.features.shaderInt64 = deviceFeatures.shaderInt64; - requestedFeatures2.features.fragmentStoresAndAtomics = deviceFeatures.fragmentStoresAndAtomics; - requestedFeatures2.features.vertexPipelineStoresAndAtomics = deviceFeatures.vertexPipelineStoresAndAtomics; - requestedExtensions.push_back(VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME); } // check extensions uint availableLayerCount; - VK_CHECK(vkEnumerateDeviceLayerProperties(gpuContext->physicalDevice, &availableLayerCount, nullptr)); + VK_CHECK(vkEnumerateDeviceLayerProperties(_gpuContext->physicalDevice, &availableLayerCount, nullptr)); _gpuDevice->layers.resize(availableLayerCount); - VK_CHECK(vkEnumerateDeviceLayerProperties(gpuContext->physicalDevice, &availableLayerCount, _gpuDevice->layers.data())); + VK_CHECK(vkEnumerateDeviceLayerProperties(_gpuContext->physicalDevice, &availableLayerCount, _gpuDevice->layers.data())); uint availableExtensionCount; - VK_CHECK(vkEnumerateDeviceExtensionProperties(gpuContext->physicalDevice, nullptr, &availableExtensionCount, nullptr)); + VK_CHECK(vkEnumerateDeviceExtensionProperties(_gpuContext->physicalDevice, nullptr, &availableExtensionCount, nullptr)); _gpuDevice->extensions.resize(availableExtensionCount); - VK_CHECK(vkEnumerateDeviceExtensionProperties(gpuContext->physicalDevice, nullptr, &availableExtensionCount, _gpuDevice->extensions.data())); + VK_CHECK(vkEnumerateDeviceExtensionProperties(_gpuContext->physicalDevice, nullptr, &availableExtensionCount, _gpuDevice->extensions.data())); // just filter out the unsupported layers & extensions for (const char *layer : requestedLayers) { @@ -171,12 +154,12 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { } // prepare the device queues - uint queueFamilyPropertiesCount = utils::toUint(gpuContext->queueFamilyProperties.size()); + uint queueFamilyPropertiesCount = utils::toUint(_gpuContext->queueFamilyProperties.size()); vector queueCreateInfos(queueFamilyPropertiesCount, {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}); vector> queuePriorities(queueFamilyPropertiesCount); for (uint queueFamilyIndex = 0U; queueFamilyIndex < queueFamilyPropertiesCount; ++queueFamilyIndex) { - const VkQueueFamilyProperties &queueFamilyProperty = gpuContext->queueFamilyProperties[queueFamilyIndex]; + const VkQueueFamilyProperties &queueFamilyProperty = _gpuContext->queueFamilyProperties[queueFamilyIndex]; queuePriorities[queueFamilyIndex].resize(queueFamilyProperty.queueCount, 1.0F); @@ -195,8 +178,7 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { deviceCreateInfo.ppEnabledLayerNames = _layers.data(); deviceCreateInfo.enabledExtensionCount = utils::toUint(_extensions.size()); deviceCreateInfo.ppEnabledExtensionNames = _extensions.data(); - if (_gpuDevice->minorVersion < 1 && - !context->checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { + if (_gpuDevice->minorVersion < 1 && !_gpuContext->checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { deviceCreateInfo.pEnabledFeatures = &requestedFeatures2.features; } else { deviceCreateInfo.pNext = &requestedFeatures2; @@ -206,12 +188,43 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { } } - VK_CHECK(vkCreateDevice(gpuContext->physicalDevice, &deviceCreateInfo, nullptr, &_gpuDevice->vkDevice)); + VK_CHECK(vkCreateDevice(_gpuContext->physicalDevice, &deviceCreateInfo, nullptr, &_gpuDevice->vkDevice)); volkLoadDevice(_gpuDevice->vkDevice); + SPIRVUtils::getInstance()->initialize(static_cast(_gpuDevice->minorVersion)); + ///////////////////// Gather Device Properties ///////////////////// + auto findPreferredDepthFormat = [this](const VkFormat *formats, uint32_t count, VkFormat *pFormat) { + for (uint32_t i = 0; i < count; ++i) { + VkFormat format = formats[i]; + VkFormatProperties formatProperties; + vkGetPhysicalDeviceFormatProperties(_gpuContext->physicalDevice, format, &formatProperties); + // Format must support depth stencil attachment for optimal tiling + if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { + if (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { + *pFormat = format; + break; + } + } + } + }; + + VkFormat depthFormatPriorityList[]{ + VK_FORMAT_D32_SFLOAT, + VK_FORMAT_X8_D24_UNORM_PACK32, + VK_FORMAT_D16_UNORM, + }; + findPreferredDepthFormat(depthFormatPriorityList, 3, &_gpuDevice->depthFormat); + + VkFormat depthStencilFormatPriorityList[]{ + VK_FORMAT_D32_SFLOAT_S8_UINT, + VK_FORMAT_D24_UNORM_S8_UINT, + VK_FORMAT_D16_UNORM_S8_UINT, + }; + findPreferredDepthFormat(depthStencilFormatPriorityList, 3, &_gpuDevice->depthStencilFormat); + _features[toNumber(Feature::COLOR_FLOAT)] = true; _features[toNumber(Feature::COLOR_HALF_FLOAT)] = true; _features[toNumber(Feature::TEXTURE_FLOAT)] = true; @@ -239,7 +252,7 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { VkFormatFeatureFlags requiredFeatures = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; VkFormatProperties formatProperties; - vkGetPhysicalDeviceFormatProperties(gpuContext->physicalDevice, VK_FORMAT_R8G8B8_UNORM, &formatProperties); + vkGetPhysicalDeviceFormatProperties(_gpuContext->physicalDevice, VK_FORMAT_R8G8B8_UNORM, &formatProperties); if (formatProperties.optimalTilingFeatures & requiredFeatures) { _features[toNumber(Feature::FORMAT_RGB8)] = true; } @@ -254,7 +267,7 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { compressedFmts += "astc "; } - const VkPhysicalDeviceLimits &limits = gpuContext->physicalDeviceProperties.limits; + const VkPhysicalDeviceLimits &limits = _gpuContext->physicalDeviceProperties.limits; _caps.maxVertexAttributes = limits.maxVertexInputAttributes; _caps.maxVertexUniformVectors = limits.maxPerStageDescriptorUniformBuffers; _caps.maxFragmentUniformVectors = limits.maxPerStageDescriptorUniformBuffers; @@ -267,15 +280,15 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { _caps.maxTextureSize = limits.maxImageDimension2D; _caps.maxCubeMapTextureSize = limits.maxImageDimensionCube; _caps.uboOffsetAlignment = static_cast(limits.minUniformBufferOffsetAlignment); - mapDepthStencilBits(_context->getDepthStencilFormat(), &_caps.depthBits, &_caps.stencilBits); // compute shaders _caps.maxComputeSharedMemorySize = limits.maxComputeSharedMemorySize; _caps.maxComputeWorkGroupInvocations = limits.maxComputeWorkGroupInvocations; _caps.maxComputeWorkGroupCount = {limits.maxComputeWorkGroupCount[0], limits.maxComputeWorkGroupCount[1], limits.maxComputeWorkGroupCount[2]}; _caps.maxComputeWorkGroupSize = {limits.maxComputeWorkGroupSize[0], limits.maxComputeWorkGroupSize[1], limits.maxComputeWorkGroupSize[2]}; #if defined(VK_USE_PLATFORM_ANDROID_KHR) - _caps.maxComputeWorkGroupInvocations = 64; // UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size -#endif // defined(VK_USE_PLATFORM_ANDROID_KHR) + // UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size + _caps.maxComputeWorkGroupInvocations = 64; +#endif // defined(VK_USE_PLATFORM_ANDROID_KHR) ///////////////////// Resource Initialization ///////////////////// @@ -289,9 +302,9 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { _cmdBuff = createCommandBuffer(cmdBuffInfo); VmaAllocatorCreateInfo allocatorInfo{}; - allocatorInfo.physicalDevice = gpuContext->physicalDevice; + allocatorInfo.physicalDevice = _gpuContext->physicalDevice; allocatorInfo.device = _gpuDevice->vkDevice; - allocatorInfo.instance = gpuContext->vkInstance; + allocatorInfo.instance = _gpuContext->vkInstance; VmaVulkanFunctions vmaVulkanFunc{}; vmaVulkanFunc.vkAllocateMemory = vkAllocateMemory; @@ -342,7 +355,7 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { VK_CHECK(vmaCreateAllocator(&allocatorInfo, &_gpuDevice->memoryAllocator)); - uint backBufferCount = gpuContext->swapchainCreateInfo.minImageCount; + uint backBufferCount = _gpuDevice->backBufferCount; for (uint i = 0U; i < backBufferCount; i++) { _gpuFencePools.push_back(CC_NEW(CCVKGPUFencePool(_gpuDevice))); _gpuRecycleBins.push_back(CC_NEW(CCVKGPURecycleBin(_gpuDevice))); @@ -382,7 +395,8 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { gpuTransportHub()->checkIn( [&barrier](const CCVKGPUCommandBuffer *gpuCommandBuffer) { cmdFuncCCVKImageMemoryBarrier(gpuCommandBuffer, barrier); - }); + }, + true); _gpuDevice->defaultBuffer.usage = BufferUsage::UNIFORM; _gpuDevice->defaultBuffer.memUsage = MemoryUsage::HOST | MemoryUsage::DEVICE; @@ -393,30 +407,16 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { VkPipelineCacheCreateInfo pipelineCacheInfo{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; VK_CHECK(vkCreatePipelineCache(_gpuDevice->vkDevice, &pipelineCacheInfo, nullptr, &_gpuDevice->vkPipelineCache)); - for (uint i = 0U; i < gpuContext->swapchainCreateInfo.minImageCount; i++) { - TextureInfo depthStencilTexInfo; - depthStencilTexInfo.type = TextureType::TEX2D; - depthStencilTexInfo.usage = TextureUsageBit::DEPTH_STENCIL_ATTACHMENT; - depthStencilTexInfo.format = _context->getDepthStencilFormat(); - depthStencilTexInfo.width = _width; - depthStencilTexInfo.height = _height; - auto *texture = static_cast(createTexture(depthStencilTexInfo)); - _depthStencilTextures.push_back(texture); - } - - _gpuDevice->swapchain = _gpuSwapchain = CC_NEW(CCVKGPUSwapchain); - checkSwapchainStatus(); - ///////////////////// Print Debug Info ///////////////////// String instanceLayers; String instanceExtensions; String deviceLayers; String deviceExtensions; - for (const char *layer : static_cast(_context)->getLayers()) { + for (const char *layer : _gpuContext->layers) { instanceLayers += layer + String(" "); } - for (const char *extension : static_cast(_context)->getExtensions()) { + for (const char *extension : _gpuContext->extensions) { instanceExtensions += extension + String(" "); } for (const char *layer : _layers) { @@ -426,9 +426,9 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { deviceExtensions += extension + String(" "); } - uint32_t apiVersion = gpuContext->physicalDeviceProperties.apiVersion; - _renderer = gpuContext->physicalDeviceProperties.deviceName; - _vendor = mapVendorName(gpuContext->physicalDeviceProperties.vendorID); + uint32_t apiVersion = _gpuContext->physicalDeviceProperties.apiVersion; + _renderer = _gpuContext->physicalDeviceProperties.deviceName; + _vendor = mapVendorName(_gpuContext->physicalDeviceProperties.vendorID); _version = StringUtil::format("%d.%d.%d", VK_VERSION_MAJOR(apiVersion), VK_VERSION_MINOR(apiVersion), VK_VERSION_PATCH(apiVersion)); @@ -436,13 +436,11 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); CC_LOG_INFO("VERSION: %s", _version.c_str()); - CC_LOG_INFO("SCREEN_SIZE: %d x %d", _width, _height); CC_LOG_INFO("INSTANCE_LAYERS: %s", instanceLayers.c_str()); CC_LOG_INFO("INSTANCE_EXTENSIONS: %s", instanceExtensions.c_str()); CC_LOG_INFO("DEVICE_LAYERS: %s", deviceLayers.c_str()); CC_LOG_INFO("DEVICE_EXTENSIONS: %s", deviceExtensions.c_str()); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); - CC_LOG_INFO("SWAPCHAIN_IMAGE_COUNT: %d", gpuContext->swapchainCreateInfo.minImageCount); return true; } @@ -450,6 +448,8 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { void CCVKDevice::doDestroy() { waitAllFences(); + SPIRVUtils::getInstance()->destroy(); + for (CCVKTexture *texture : _depthStencilTextures) { CC_SAFE_DESTROY(texture) } @@ -465,7 +465,7 @@ void CCVKDevice::doDestroy() { CC_SAFE_DELETE(_gpuBarrierManager) CC_SAFE_DELETE(_gpuDescriptorSetHub) - uint backBufferCount = static_cast(_context)->gpuContext()->swapchainCreateInfo.minImageCount; + uint backBufferCount = _gpuDevice->backBufferCount; for (uint i = 0U; i < backBufferCount; i++) { _gpuRecycleBins[i]->clear(); @@ -477,12 +477,6 @@ void CCVKDevice::doDestroy() { _gpuRecycleBins.clear(); _gpuFencePools.clear(); - if (_gpuSwapchain) { - destroySwapchain(); - CC_DELETE(_gpuSwapchain); - _gpuSwapchain = nullptr; - } - if (_gpuDevice) { if (_gpuDevice->vkPipelineCache) { vkDestroyPipelineCache(_gpuDevice->vkDevice, _gpuDevice->vkPipelineCache, nullptr); @@ -532,70 +526,130 @@ void CCVKDevice::doDestroy() { _gpuDevice = nullptr; } - CC_SAFE_DESTROY(_context) + CC_SAFE_DESTROY(_gpuContext) } -// no-op since we maintain surface size internally -void CCVKDevice::resize(uint width, uint height) {} +namespace { +vector vkSwapchains; +vector vkSwapchainIndices; +vector gpuSwapchains; +vector vkAcquireBarriers; +vector vkPresentBarriers; -void CCVKDevice::acquire() { +VkImageMemoryBarrier acquireBarrier{ + VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + nullptr, + 0, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_QUEUE_FAMILY_IGNORED, + VK_QUEUE_FAMILY_IGNORED, + 0, + {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, +}; +VkImageMemoryBarrier presentBarrier{ + VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + nullptr, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + 0, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_QUEUE_FAMILY_IGNORED, + VK_QUEUE_FAMILY_IGNORED, + 0, + {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, +}; +} // namespace + +void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { auto *queue = static_cast(_queue); + queue->gpuQueue()->lastSignaledSemaphores.clear(); + vkSwapchainIndices.clear(); + gpuSwapchains.clear(); + vkSwapchains.clear(); + vkAcquireBarriers.resize(count, acquireBarrier); + vkPresentBarriers.resize(count, presentBarrier); - if (!checkSwapchainStatus()) return; - - queue->_numDrawCalls = 0; - queue->_numInstances = 0; - queue->_numTriangles = 0; - queue->gpuQueue()->nextWaitSemaphore = VK_NULL_HANDLE; - queue->gpuQueue()->nextSignalSemaphore = VK_NULL_HANDLE; + for (uint32_t i = 0U; i < count; ++i) { + auto *swapchain = static_cast(swapchains[i]); + if (swapchain->gpuSwapchain()->lastPresentResult == VK_NOT_READY) { + if (!swapchain->checkSwapchainStatus()) continue; + } + vkSwapchains.push_back(swapchain->gpuSwapchain()->vkSwapchain); + gpuSwapchains.push_back(swapchain->gpuSwapchain()); + vkSwapchainIndices.push_back(swapchain->gpuSwapchain()->curImageIndex); + } _gpuDescriptorSetHub->flush(); - _gpuSemaphorePool->reset(); - VkSemaphore acquireSemaphore = _gpuSemaphorePool->alloc(); - VK_CHECK(vkAcquireNextImageKHR(_gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, ~0ULL, - acquireSemaphore, VK_NULL_HANDLE, &_gpuSwapchain->curImageIndex)); -#if !defined(VK_USE_PLATFORM_METAL_EXT) - // MoltenVK seems to be not consistent on this index - CCASSERT(_gpuDevice->curBackBufferIndex == _gpuSwapchain->curImageIndex, "wrong image index?"); -#endif // defined(VK_USE_PLATFORM_METAL_EXT) + for (uint32_t i = 0; i < vkSwapchains.size(); ++i) { + VkSemaphore acquireSemaphore = _gpuSemaphorePool->alloc(); + VK_CHECK(vkAcquireNextImageKHR(_gpuDevice->vkDevice, vkSwapchains[i], ~0ULL, + acquireSemaphore, VK_NULL_HANDLE, &vkSwapchainIndices[i])); + gpuSwapchains[i]->curImageIndex = vkSwapchainIndices[i]; + queue->gpuQueue()->lastSignaledSemaphores.push_back(acquireSemaphore); - queue->gpuQueue()->nextWaitSemaphore = acquireSemaphore; - queue->gpuQueue()->nextSignalSemaphore = _gpuSemaphorePool->alloc(); + // swapchain indices may be different + //CCASSERT(_gpuDevice->curBackBufferIndex == vkSwapchainIndices[i], "wrong image index?"); + + vkAcquireBarriers[i].image = gpuSwapchains[i]->swapchainImages[vkSwapchainIndices[i]]; + vkPresentBarriers[i].image = gpuSwapchains[i]->swapchainImages[vkSwapchainIndices[i]]; + } + + _gpuTransportHub->checkIn( + [&](const CCVKGPUCommandBuffer *gpuCommandBuffer) { + vkCmdPipelineBarrier(gpuCommandBuffer->vkCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + 0, 0, nullptr, 0, nullptr, utils::toUint(vkSwapchains.size()), vkAcquireBarriers.data()); + }, + false, false); + + _gpuTransportHub->checkIn( + [&](const CCVKGPUCommandBuffer *gpuCommandBuffer) { + vkCmdPipelineBarrier(gpuCommandBuffer->vkCommandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, nullptr, 0, nullptr, utils::toUint(vkSwapchains.size()), vkPresentBarriers.data()); + }, + false, true); } void CCVKDevice::present() { - auto *queue = static_cast(_queue); - _numDrawCalls = queue->_numDrawCalls; - _numInstances = queue->_numInstances; - _numTriangles = queue->_numTriangles; + auto *queue = static_cast(_queue); + _numDrawCalls = queue->_numDrawCalls; + _numInstances = queue->_numInstances; + _numTriangles = queue->_numTriangles; + queue->_numDrawCalls = 0; + queue->_numInstances = 0; + queue->_numTriangles = 0; - if (queue->gpuQueue()->nextWaitSemaphore) { // don't present if not acquired + if (!_gpuTransportHub->empty(false)) _gpuTransportHub->packageForFlight(false); + if (!_gpuTransportHub->empty(true)) _gpuTransportHub->packageForFlight(true); + + if (!vkSwapchains.empty()) { // don't present if not acquired VkPresentInfoKHR presentInfo{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; - presentInfo.waitSemaphoreCount = 1; - presentInfo.pWaitSemaphores = &queue->gpuQueue()->nextWaitSemaphore; - presentInfo.swapchainCount = 1; - presentInfo.pSwapchains = &_gpuSwapchain->vkSwapchain; - presentInfo.pImageIndices = &_gpuSwapchain->curImageIndex; + presentInfo.waitSemaphoreCount = utils::toUint(queue->gpuQueue()->lastSignaledSemaphores.size()); + presentInfo.pWaitSemaphores = queue->gpuQueue()->lastSignaledSemaphores.data(); + presentInfo.swapchainCount = utils::toUint(vkSwapchains.size()); + presentInfo.pSwapchains = vkSwapchains.data(); + presentInfo.pImageIndices = vkSwapchainIndices.data(); VkResult res = vkQueuePresentKHR(queue->gpuQueue()->vkQueue, &presentInfo); -#ifndef DISABLE_PRE_TRANSFORM - if (res) _swapchainReady = false; -#endif - - _gpuDevice->curBackBufferIndex = (_gpuDevice->curBackBufferIndex + 1) % _gpuDevice->backBufferCount; - - uint fenceCount = gpuFencePool()->size(); - if (fenceCount) { - VK_CHECK(vkWaitForFences(_gpuDevice->vkDevice, fenceCount, - gpuFencePool()->data(), VK_TRUE, DEFAULT_TIMEOUT)); + for (auto *gpuSwapchain : gpuSwapchains) { + gpuSwapchain->lastPresentResult = res; } - - gpuFencePool()->reset(); - gpuRecycleBin()->clear(); - gpuStagingBufferPool()->reset(); } + + _gpuDevice->curBackBufferIndex = (_gpuDevice->curBackBufferIndex + 1) % _gpuDevice->backBufferCount; + + uint fenceCount = gpuFencePool()->size(); + if (fenceCount) { + VK_CHECK(vkWaitForFences(_gpuDevice->vkDevice, fenceCount, + gpuFencePool()->data(), VK_TRUE, DEFAULT_TIMEOUT)); + } + + gpuFencePool()->reset(); + gpuRecycleBin()->clear(); + gpuStagingBufferPool()->reset(); } CCVKGPUFencePool * CCVKDevice::gpuFencePool() { return _gpuFencePools[_gpuDevice->curBackBufferIndex]; } @@ -603,12 +657,16 @@ CCVKGPURecycleBin * CCVKDevice::gpuRecycleBin() { return _gpuRecycleBins[_ CCVKGPUStagingBufferPool *CCVKDevice::gpuStagingBufferPool() { return _gpuStagingBufferPools[_gpuDevice->curBackBufferIndex]; } void CCVKDevice::waitAllFences() { - vector fences; + static vector fences; + fences.clear(); + for (auto *fencePool : _gpuFencePools) { fences.insert(fences.end(), fencePool->data(), fencePool->data() + fencePool->size()); } + if (!fences.empty()) { - VK_CHECK(vkWaitForFences(_gpuDevice->vkDevice, fences.size(), fences.data(), VK_TRUE, DEFAULT_TIMEOUT)); + VK_CHECK(vkWaitForFences(_gpuDevice->vkDevice, utils::toUint(fences.size()), fences.data(), VK_TRUE, DEFAULT_TIMEOUT)); + for (auto *fencePool : _gpuFencePools) { fencePool->reset(); } @@ -623,6 +681,10 @@ Queue *CCVKDevice::createQueue() { return CC_NEW(CCVKQueue); } +Swapchain *CCVKDevice::createSwapchain() { + return CC_NEW(CCVKSwapchain); +} + Buffer *CCVKDevice::createBuffer() { return CC_NEW(CCVKBuffer); } @@ -631,10 +693,6 @@ Texture *CCVKDevice::createTexture() { return CC_NEW(CCVKTexture); } -Sampler *CCVKDevice::createSampler() { - return CC_NEW(CCVKSampler); -} - Shader *CCVKDevice::createShader() { return CC_NEW(CCVKShader); } @@ -667,12 +725,16 @@ PipelineState *CCVKDevice::createPipelineState() { return CC_NEW(CCVKPipelineState); } -GlobalBarrier *CCVKDevice::createGlobalBarrier() { - return CC_NEW(CCVKGlobalBarrier); +Sampler *CCVKDevice::createSampler(const SamplerInfo &info) { + return CC_NEW(CCVKSampler(info)); } -TextureBarrier *CCVKDevice::createTextureBarrier() { - return CC_NEW(CCVKTextureBarrier); +GlobalBarrier *CCVKDevice::createGlobalBarrier(const GlobalBarrierInfo &info) { + return CC_NEW(CCVKGlobalBarrier(info)); +} + +TextureBarrier *CCVKDevice::createTextureBarrier(const TextureBarrierInfo &info) { + return CC_NEW(CCVKTextureBarrier(info)); } void CCVKDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { @@ -695,7 +757,7 @@ void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffe } CCVKGPUBuffer stagingBuffer; stagingBuffer.size = totalSize; - uint texelSize = GFX_FORMAT_INFOS[static_cast(format)].size; + uint texelSize = GFX_FORMAT_INFOS[toNumber(format)].size; gpuStagingBufferPool()->alloc(&stagingBuffer, texelSize); waitAllFences(); @@ -712,165 +774,6 @@ void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffe } } -bool CCVKDevice::checkSwapchainStatus() { - CCVKGPUContext *context = static_cast(_context)->gpuContext(); - - VkSurfaceCapabilitiesKHR surfaceCapabilities; - VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(context->physicalDevice, context->vkSurface, &surfaceCapabilities)); - - uint newWidth = surfaceCapabilities.currentExtent.width; - uint newHeight = surfaceCapabilities.currentExtent.height; - - VkSurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform; -#ifdef DISABLE_PRE_TRANSFORM - preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; -#endif - - if (preTransform & TRANSFORMS_THAT_REQUIRE_FLIPPING) { - newHeight = surfaceCapabilities.currentExtent.width; - newWidth = surfaceCapabilities.currentExtent.height; - } - - if (context->swapchainCreateInfo.preTransform == preTransform && - context->swapchainCreateInfo.imageExtent.width == newWidth && - context->swapchainCreateInfo.imageExtent.height == newHeight && _swapchainReady) { - return true; - } - - if (newWidth == static_cast(-1)) { - context->swapchainCreateInfo.imageExtent.width = _width; - context->swapchainCreateInfo.imageExtent.height = _height; - } else { - _width = context->swapchainCreateInfo.imageExtent.width = newWidth; - _height = context->swapchainCreateInfo.imageExtent.height = newHeight; - } - - if (newWidth == 0 || newHeight == 0) { - _swapchainReady = false; - return false; - } - - _transform = mapSurfaceTransform(preTransform); - context->swapchainCreateInfo.preTransform = preTransform; - context->swapchainCreateInfo.surface = context->vkSurface; - context->swapchainCreateInfo.oldSwapchain = _gpuSwapchain->vkSwapchain; - - CC_LOG_INFO("Resizing surface: %dx%d, surface rotation: %d degrees", newWidth, newHeight, (uint)_transform * 90); - - waitAllFences(); - - VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; - VK_CHECK(vkCreateSwapchainKHR(_gpuDevice->vkDevice, &context->swapchainCreateInfo, nullptr, &vkSwapchain)); - - destroySwapchain(); - - _gpuDevice->curBackBufferIndex = 0U; - _gpuSwapchain->curImageIndex = 0; - _gpuSwapchain->vkSwapchain = vkSwapchain; - - uint imageCount; - VK_CHECK(vkGetSwapchainImagesKHR(_gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, nullptr)); - _gpuSwapchain->swapchainImages.resize(imageCount); - VK_CHECK(vkGetSwapchainImagesKHR(_gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, _gpuSwapchain->swapchainImages.data())); - - CCASSERT(imageCount == context->swapchainCreateInfo.minImageCount, "swapchain image count assumption is broken"); - - _gpuSwapchain->vkSwapchainImageViews.resize(imageCount); - for (uint i = 0U; i < imageCount; i++) { - _depthStencilTextures[i]->resize(_width, _height); - _gpuSwapchain->depthStencilImages.push_back(static_cast(_depthStencilTextures[i])->gpuTexture()->vkImage); - _gpuSwapchain->depthStencilImageViews.push_back(static_cast(_depthStencilTextures[i])->gpuTextureView()->vkImageView); - - VkImageViewCreateInfo imageViewCreateInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - imageViewCreateInfo.image = _gpuSwapchain->swapchainImages[i]; - imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - imageViewCreateInfo.format = context->swapchainCreateInfo.imageFormat; - imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - imageViewCreateInfo.subresourceRange.levelCount = 1; - imageViewCreateInfo.subresourceRange.layerCount = 1; - - VK_CHECK(vkCreateImageView(_gpuDevice->vkDevice, &imageViewCreateInfo, nullptr, &_gpuSwapchain->vkSwapchainImageViews[i])); - } - - bool hasStencil = GFX_FORMAT_INFOS[toNumber(_context->getDepthStencilFormat())].hasStencil; - vector barriers(imageCount * 2, VkImageMemoryBarrier{}); - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - ThsvsImageBarrier tempBarrier{}; - tempBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - tempBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - tempBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; - tempBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - VkPipelineStageFlags tempSrcStageMask = 0; - VkPipelineStageFlags tempDstStageMask = 0; - for (uint i = 0U; i < imageCount; i++) { - tempBarrier.nextAccessCount = 1; - tempBarrier.pNextAccesses = &THSVS_ACCESS_TYPES[toNumber(AccessType::COLOR_ATTACHMENT_WRITE)]; - tempBarrier.image = _gpuSwapchain->swapchainImages[i]; - tempBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[i]); - srcStageMask |= tempSrcStageMask; - dstStageMask |= tempDstStageMask; - - tempBarrier.nextAccessCount = 1; - tempBarrier.pNextAccesses = &THSVS_ACCESS_TYPES[toNumber(AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE)]; - tempBarrier.image = _gpuSwapchain->depthStencilImages[i]; - tempBarrier.subresourceRange.aspectMask = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[imageCount + i]); - srcStageMask |= tempSrcStageMask; - dstStageMask |= tempDstStageMask; - } - gpuTransportHub()->checkIn( - [&](const CCVKGPUCommandBuffer *gpuCommandBuffer) { - vkCmdPipelineBarrier(gpuCommandBuffer->vkCommandBuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, imageCount, barriers.data()); - }, - true); // submit immediately - - _gpuSwapchain->swapchainImageAccessTypes.assign(imageCount, {THSVS_ACCESS_PRESENT}); - _gpuSwapchain->depthStencilImageAccessTypes.assign(imageCount, {THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ}); - - for (auto &it : _gpuSwapchain->vkSwapchainFramebufferListMap) { - cmdFuncCCVKCreateFramebuffer(this, it.first); - } - - return _swapchainReady = true; -} - -void CCVKDevice::destroySwapchain() { - if (_gpuSwapchain->vkSwapchain != VK_NULL_HANDLE) { - _gpuSwapchain->swapchainImageAccessTypes.clear(); - _gpuSwapchain->depthStencilImageAccessTypes.clear(); - - _gpuSwapchain->depthStencilImageViews.clear(); - _gpuSwapchain->depthStencilImages.clear(); - - for (auto &it : _gpuSwapchain->vkSwapchainFramebufferListMap) { - FramebufferList &list = it.second; - for (VkFramebuffer framebuffer : list) { - vkDestroyFramebuffer(_gpuDevice->vkDevice, framebuffer, nullptr); - } - list.clear(); - } - - for (VkImageView imageView : _gpuSwapchain->vkSwapchainImageViews) { - vkDestroyImageView(_gpuDevice->vkDevice, imageView, nullptr); - } - _gpuSwapchain->vkSwapchainImageViews.clear(); - _gpuSwapchain->swapchainImages.clear(); - - vkDestroySwapchainKHR(_gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, nullptr); - _gpuSwapchain->vkSwapchain = VK_NULL_HANDLE; - } -} - -void CCVKDevice::releaseSurface(uintptr_t windowHandle) { - static_cast(_context)->releaseSurface(windowHandle); -} - -void CCVKDevice::acquireSurface(uintptr_t windowHandle) { - static_cast(_context)->acquireSurface(windowHandle); -} - //////////////////////////// Function Fallbacks ///////////////////////////////////////// static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index 840f4aba65..1ce1bc2b4f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -35,7 +35,6 @@ class CCVKTexture; class CCVKGPUDevice; class CCVKGPUContext; -class CCVKGPUSwapchain; class CCVKGPUBufferHub; class CCVKGPUTransportHub; @@ -72,8 +71,7 @@ public: using Device::createTexture; using Device::createTextureBarrier; - void resize(uint width, uint height) override; - void acquire() override; + void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; inline bool checkExtension(const String &extension) const { @@ -82,9 +80,8 @@ public: }); } - CCVKGPUContext * gpuContext() const; - inline CCVKGPUDevice * gpuDevice() const { return _gpuDevice; } - inline CCVKGPUSwapchain *gpuSwapchain() { return _gpuSwapchain; } + inline CCVKGPUDevice * gpuDevice() const { return _gpuDevice; } + inline CCVKGPUContext *gpuContext() { return _gpuContext; } inline CCVKGPUBufferHub * gpuBufferHub() { return _gpuBufferHub; } inline CCVKGPUTransportHub * gpuTransportHub() { return _gpuTransportHub; } @@ -109,9 +106,9 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; - Sampler * createSampler() override; Shader * createShader() override; InputAssembler * createInputAssembler() override; RenderPass * createRenderPass() override; @@ -120,19 +117,19 @@ protected: DescriptorSetLayout *createDescriptorSetLayout() override; PipelineLayout * createPipelineLayout() override; PipelineState * createPipelineState() override; - GlobalBarrier * createGlobalBarrier() override; - TextureBarrier * createTextureBarrier() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + + Sampler * createSampler(const SamplerInfo &info) override; + GlobalBarrier * createGlobalBarrier(const GlobalBarrierInfo &info) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; + + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; void destroySwapchain(); bool checkSwapchainStatus(); - void releaseSurface(uintptr_t windowHandle) override; - void acquireSurface(uintptr_t windowHandle) override; - - CCVKGPUDevice * _gpuDevice = nullptr; - CCVKGPUSwapchain * _gpuSwapchain = nullptr; + CCVKGPUDevice * _gpuDevice = nullptr; + CCVKGPUContext * _gpuContext = nullptr; vector _depthStencilTextures; vector _gpuFencePools; @@ -148,8 +145,6 @@ protected: vector _layers; vector _extensions; - - bool _swapchainReady = false; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp index 470d673eee..b829333596 100644 --- a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp @@ -34,7 +34,9 @@ namespace cc { namespace gfx { -CCVKFramebuffer::CCVKFramebuffer() = default; +CCVKFramebuffer::CCVKFramebuffer() { + _typedID = generateObjectID(); +} CCVKFramebuffer::~CCVKFramebuffer() { destroy(); diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp new file mode 100644 index 0000000000..c78d86f765 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp @@ -0,0 +1,333 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "VKStd.h" + +#include "VKGPUObjects.h" + +namespace cc { +namespace gfx { + +namespace { + +constexpr uint FORCE_MINOR_VERSION = 0; // 0 for default version, otherwise minorVersion = (FORCE_MINOR_VERSION - 1) +constexpr uint DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled + +#define FORCE_ENABLE_VALIDATION 0 +#define FORCE_DISABLE_VALIDATION 1 + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION +VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT *callbackData, + void * userData) { + if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { + CC_LOG_ERROR("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); + CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); + return VK_FALSE; + } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { + CC_LOG_WARNING("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); + return VK_FALSE; + } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { + //CC_LOG_INFO("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); + return VK_FALSE; + } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) { + //CC_LOG_DEBUG("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); + return VK_FALSE; + } + CC_LOG_ERROR("%s: %s", callbackData->pMessageIdName, callbackData->pMessage); + return VK_FALSE; +} + +VKAPI_ATTR VkBool32 VKAPI_CALL debugReportCallback(VkDebugReportFlagsEXT flags, + VkDebugReportObjectTypeEXT type, + uint64_t object, + size_t location, + int32_t messageCode, + const char * layerPrefix, + const char * message, + void * userData) { + if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + CC_LOG_ERROR("%s: %s", layerPrefix, message); + CCASSERT(DISABLE_VALIDATION_ASSERTIONS, "Validation Error"); + return VK_FALSE; + } else if (flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)) { + CC_LOG_WARNING("%s: %s", layerPrefix, message); + return VK_FALSE; + } else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + //CC_LOG_INFO("%s: %s", layerPrefix, message); + return VK_FALSE; + } else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + //CC_LOG_DEBUG("%s: %s", layerPrefix, message); + return VK_FALSE; + } + CC_LOG_ERROR("%s: %s", layerPrefix, message); + return VK_FALSE; +} +#endif +} // namespace + +bool CCVKGPUContext::initialize() { + // only enable the absolute essentials + vector requestedLayers{ + "VK_LAYER_KHRONOS_synchronization2"}; + vector requestedExtensions{ + VK_KHR_SURFACE_EXTENSION_NAME, + }; + + ///////////////////// Instance Creation ///////////////////// + + if (volkInitialize()) { + return false; + } + + uint apiVersion = VK_API_VERSION_1_0; + if (vkEnumerateInstanceVersion) { + vkEnumerateInstanceVersion(&apiVersion); + if (FORCE_MINOR_VERSION) { + apiVersion = VK_MAKE_VERSION(1, FORCE_MINOR_VERSION - 1, 0); + } + } + + minorVersion = VK_VERSION_MINOR(apiVersion); + if (minorVersion < 1) { + requestedExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + } + + uint availableLayerCount; + VK_CHECK(vkEnumerateInstanceLayerProperties(&availableLayerCount, nullptr)); + vector supportedLayers(availableLayerCount); + VK_CHECK(vkEnumerateInstanceLayerProperties(&availableLayerCount, supportedLayers.data())); + + uint availableExtensionCount; + VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &availableExtensionCount, nullptr)); + vector supportedExtensions(availableExtensionCount); + VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &availableExtensionCount, supportedExtensions.data())); + +#if defined(VK_USE_PLATFORM_ANDROID_KHR) + requestedExtensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME); +#elif defined(VK_USE_PLATFORM_WIN32_KHR) + requestedExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); +#elif defined(VK_USE_PLATFORM_METAL_EXT) + requestedExtensions.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME); +#elif defined(VK_USE_PLATFORM_WAYLAND_KHR) + requestedExtensions.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME); +#elif defined(VK_USE_PLATFORM_XCB_KHR) + requestedExtensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME); +#else + #pragma error Platform not supported +#endif + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION + // Determine the optimal validation layers to enable that are necessary for useful debugging + vector> validationLayerPriorityList{ + // The preferred validation layer is "VK_LAYER_KHRONOS_validation" + {"VK_LAYER_KHRONOS_validation"}, + + // Otherwise we fallback to using the LunarG meta layer + {"VK_LAYER_LUNARG_standard_validation"}, + + // Otherwise we attempt to enable the individual layers that compose the LunarG meta layer since it doesn't exist + { + "VK_LAYER_GOOGLE_threading", + "VK_LAYER_LUNARG_parameter_validation", + "VK_LAYER_LUNARG_object_tracker", + "VK_LAYER_LUNARG_core_validation", + "VK_LAYER_GOOGLE_unique_objects", + }, + + // Otherwise as a last resort we fallback to attempting to enable the LunarG core layer + {"VK_LAYER_LUNARG_core_validation"}, + }; + for (vector &validationLayers : validationLayerPriorityList) { + bool found = true; + for (const char *layer : validationLayers) { + if (!isLayerSupported(layer, supportedLayers)) { + found = false; + break; + } + } + if (found) { + requestedLayers.insert(requestedLayers.end(), validationLayers.begin(), validationLayers.end()); + break; + } + } + + // Check if VK_EXT_debug_utils is supported, which supersedes VK_EXT_Debug_Report + bool debugUtils = false; + if (isExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, supportedExtensions)) { + debugUtils = true; + requestedExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + } else { + requestedExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); + } +#endif + + // just filter out the unsupported layers & extensions + for (const char *layer : requestedLayers) { + if (isLayerSupported(layer, supportedLayers)) { + layers.push_back(layer); + } + } + for (const char *extension : requestedExtensions) { + if (isExtensionSupported(extension, supportedExtensions)) { + extensions.push_back(extension); + } + } + + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.pEngineName = "Cocos Creator"; + app.apiVersion = apiVersion; + + VkInstanceCreateInfo instanceInfo{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + instanceInfo.pApplicationInfo = &app; + instanceInfo.enabledExtensionCount = utils::toUint(extensions.size()); + instanceInfo.ppEnabledExtensionNames = extensions.data(); + instanceInfo.enabledLayerCount = utils::toUint(layers.size()); + instanceInfo.ppEnabledLayerNames = layers.data(); + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION + VkDebugUtilsMessengerCreateInfoEXT debugUtilsCreateInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; + VkDebugReportCallbackCreateInfoEXT debugReportCreateInfo{VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT}; + if (debugUtils) { + debugUtilsCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT; + debugUtilsCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + debugUtilsCreateInfo.pfnUserCallback = debugUtilsMessengerCallback; + + instanceInfo.pNext = &debugUtilsCreateInfo; + } else { + debugReportCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | + VK_DEBUG_REPORT_WARNING_BIT_EXT | + VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | + VK_DEBUG_REPORT_INFORMATION_BIT_EXT | + VK_DEBUG_REPORT_DEBUG_BIT_EXT; + debugReportCreateInfo.pfnCallback = debugReportCallback; + + instanceInfo.pNext = &debugReportCreateInfo; + } +#endif + + // Create the Vulkan instance + VkResult res = vkCreateInstance(&instanceInfo, nullptr, &vkInstance); + if (res == VK_ERROR_LAYER_NOT_PRESENT) { + CC_LOG_ERROR("Create Vulkan instance failed due to missing layers, aborting..."); + return false; + } + + volkLoadInstanceOnly(vkInstance); + +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION + if (debugUtils) { + VK_CHECK(vkCreateDebugUtilsMessengerEXT(vkInstance, &debugUtilsCreateInfo, nullptr, &vkDebugUtilsMessenger)); + } else { + VK_CHECK(vkCreateDebugReportCallbackEXT(vkInstance, &debugReportCreateInfo, nullptr, &vkDebugReport)); + } + validationEnabled = true; +#endif + + ///////////////////// Physical Device Selection ///////////////////// + + // Querying valid physical devices on the machine + uint physicalDeviceCount{0}; + res = vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, nullptr); + + if (res || physicalDeviceCount < 1) { + return false; + } + + vector physicalDeviceHandles(physicalDeviceCount); + VK_CHECK(vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDeviceHandles.data())); + + vector physicalDevicePropertiesList(physicalDeviceCount); + + uint deviceIndex; + for (deviceIndex = 0U; deviceIndex < physicalDeviceCount; ++deviceIndex) { + VkPhysicalDeviceProperties &properties = physicalDevicePropertiesList[deviceIndex]; + vkGetPhysicalDeviceProperties(physicalDeviceHandles[deviceIndex], &properties); + } + + for (deviceIndex = 0U; deviceIndex < physicalDeviceCount; ++deviceIndex) { + VkPhysicalDeviceProperties &properties = physicalDevicePropertiesList[deviceIndex]; + if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { + break; + } + } + + if (deviceIndex == physicalDeviceCount) { + deviceIndex = 0; + } + + physicalDevice = physicalDeviceHandles[deviceIndex]; + physicalDeviceProperties = physicalDevicePropertiesList[deviceIndex]; + vkGetPhysicalDeviceFeatures(physicalDevice, &physicalDeviceFeatures); + + majorVersion = VK_VERSION_MAJOR(physicalDeviceProperties.apiVersion); + minorVersion = VK_VERSION_MINOR(physicalDeviceProperties.apiVersion); + + if (minorVersion >= 1 || checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { + physicalDeviceFeatures2.pNext = &physicalDeviceVulkan11Features; + physicalDeviceVulkan11Features.pNext = &physicalDeviceVulkan12Features; + physicalDeviceProperties2.pNext = &physicalDeviceDepthStencilResolveProperties; + if (minorVersion >= 1) { + vkGetPhysicalDeviceProperties2(physicalDevice, &physicalDeviceProperties2); + vkGetPhysicalDeviceFeatures2(physicalDevice, &physicalDeviceFeatures2); + } else { + vkGetPhysicalDeviceProperties2KHR(physicalDevice, &physicalDeviceProperties2); + vkGetPhysicalDeviceFeatures2KHR(physicalDevice, &physicalDeviceFeatures2); + } + } + + vkGetPhysicalDeviceMemoryProperties(physicalDevice, &physicalDeviceMemoryProperties); + uint queueFamilyPropertiesCount = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, nullptr); + queueFamilyProperties.resize(queueFamilyPropertiesCount); + vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, queueFamilyProperties.data()); + + return true; +} + +void CCVKGPUContext::destroy() { +#if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION + if (vkDebugUtilsMessenger != VK_NULL_HANDLE) { + vkDestroyDebugUtilsMessengerEXT(vkInstance, vkDebugUtilsMessenger, nullptr); + vkDebugUtilsMessenger = VK_NULL_HANDLE; + } + if (vkDebugReport != VK_NULL_HANDLE) { + vkDestroyDebugReportCallbackEXT(vkInstance, vkDebugReport, nullptr); + vkDebugReport = VK_NULL_HANDLE; + } +#endif + + if (vkInstance != VK_NULL_HANDLE) { + vkDestroyInstance(vkInstance, nullptr); + vkInstance = VK_NULL_HANDLE; + } +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 9144f03271..2f8c4ba9c5 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -25,13 +25,10 @@ #pragma once -#include -#include - -#include "base/CachedArray.h" - #include "VKStd.h" #include "VKUtils.h" +#include "gfx-base/GFXDef-common.h" +#include "vulkan/vulkan_core.h" #define TBB_USE_EXCEPTIONS 0 // no-rtti for now #include "tbb/concurrent_unordered_map.h" @@ -41,6 +38,9 @@ namespace gfx { class CCVKGPUContext final : public Object { public: + bool initialize(); + void destroy(); + VkInstance vkInstance = VK_NULL_HANDLE; VkDebugUtilsMessengerEXT vkDebugUtilsMessenger = VK_NULL_HANDLE; VkDebugReportCallbackEXT vkDebugReport = VK_NULL_HANDLE; @@ -55,13 +55,22 @@ public: VkPhysicalDeviceProperties2 physicalDeviceProperties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties{}; vector queueFamilyProperties; - vector queueFamilyPresentables; - VkSurfaceKHR vkSurface = VK_NULL_HANDLE; + uint32_t majorVersion = 0; + uint32_t minorVersion = 0; - VkSwapchainCreateInfoKHR swapchainCreateInfo{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + bool validationEnabled = false; - VkSampleCountFlagBits getSampleCountForAttachments(Format format, SampleCount sampleCount) const; + vector layers; + vector extensions; + + inline bool checkExtension(const String &extension) const { + return std::any_of(extensions.begin(), extensions.end(), [&extension](auto &ext) { + return std::strcmp(ext, extension.c_str()) == 0; + }); + } + + VkSampleCountFlagBits getSampleCountForAttachments(Format format, VkFormat vkFormat, SampleCount sampleCount) const; }; struct CCVKAccessInfo { @@ -89,6 +98,7 @@ public: vector sampleCounts; // per subpass }; +class CCVKGPUSwapchain; class CCVKGPUTexture final : public Object { public: TextureType type = TextureType::TEX2D; @@ -100,7 +110,7 @@ public: uint size = 0U; uint arrayLayers = 1U; uint mipLevels = 1U; - SampleCount samples = SampleCount::X1; + SampleCount samples = SampleCount::ONE; TextureFlags flags = TextureFlagBit::NONE; VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; bool memoryless = false; @@ -108,6 +118,10 @@ public: VkImage vkImage = VK_NULL_HANDLE; VmaAllocation vmaAllocation = VK_NULL_HANDLE; + CCVKGPUSwapchain * swapchain = nullptr; + vector swapchainVkImages; + vector swapchainVmaAllocations; + vector currentAccessTypes; // for barrier manager @@ -125,10 +139,11 @@ public: uint baseLayer = 0U; uint layerCount = 1U; + vector swapchainVkImageViews; + // descriptor infos VkImageView vkImageView = VK_NULL_HANDLE; }; -using CCVKGPUTextureViewList = vector; class CCVKGPUSampler final : public Object { public: @@ -140,8 +155,6 @@ public: Address addressW = Address::WRAP; uint maxAnisotropy = 0U; ComparisonFunc cmpFunc = ComparisonFunc::NEVER; - Color borderColor; - float mipLODBias = 0.0F; // descriptor infos VkSampler vkSampler; @@ -172,25 +185,31 @@ public: // for barrier manager vector renderAccessTypes; // gathered from descriptor sets ThsvsAccessType transferAccess = THSVS_ACCESS_NONE; + + VkDeviceSize getStartOffset(uint curBackBufferIndex) const { + return startOffset + instanceSize * curBackBufferIndex; + } }; -using CCVKGPUBufferList = vector; class CCVKGPUBufferView final : public Object { public: CCVKGPUBuffer *gpuBuffer = nullptr; uint offset = 0U; uint range = 0U; + + VkDeviceSize getStartOffset(uint curBackBufferIndex) const { + return gpuBuffer->getStartOffset(curBackBufferIndex) + offset; + } }; -class CCVKGPUSwapchain; class CCVKGPUFramebuffer final : public Object { public: - CCVKGPURenderPass * gpuRenderPass = nullptr; - CCVKGPUTextureViewList gpuColorViews; - CCVKGPUTextureView * gpuDepthStencilView = nullptr; - VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; - CCVKGPUSwapchain * swapchain = nullptr; - bool isOffscreen = true; + CCVKGPURenderPass * gpuRenderPass = nullptr; + vector gpuColorViews; + CCVKGPUTextureView * gpuDepthStencilView = nullptr; + VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; + CCVKGPUSwapchain * swapchain = nullptr; + bool isOffscreen = true; }; using FramebufferList = vector; @@ -199,16 +218,17 @@ using FramebufferListMapIter = FramebufferListMap::iterator; class CCVKGPUSwapchain final : public Object { public: - uint curImageIndex = 0U; - VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; - vector vkSwapchainImageViews; - FramebufferListMap vkSwapchainFramebufferListMap; - vector> swapchainImageAccessTypes; - vector> depthStencilImageAccessTypes; + VkSurfaceKHR vkSurface = VK_NULL_HANDLE; + VkSwapchainCreateInfoKHR createInfo{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + + uint curImageIndex = 0U; + VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; + FramebufferListMap vkSwapchainFramebufferListMap; + vector queueFamilyPresentables; + VkResult lastPresentResult = VK_NOT_READY; + // external references - vector swapchainImages; - vector depthStencilImages; - vector depthStencilImageViews; + vector swapchainImages; }; class CCVKGPUCommandBuffer final : public Object { @@ -222,13 +242,13 @@ public: class CCVKGPUQueue final : public Object { public: - QueueType type = QueueType::GRAPHICS; - VkQueue vkQueue = VK_NULL_HANDLE; - uint queueFamilyIndex = 0U; - VkSemaphore nextWaitSemaphore = VK_NULL_HANDLE; - VkSemaphore nextSignalSemaphore = VK_NULL_HANDLE; - VkPipelineStageFlags submitStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - CachedArray commandBuffers; + QueueType type = QueueType::GRAPHICS; + VkQueue vkQueue = VK_NULL_HANDLE; + uint queueFamilyIndex = 0U; + vector possibleQueueFamilyIndices; + vector lastSignaledSemaphores; + vector submitStageMasks; + vector commandBuffers; }; struct CCVKGPUShaderStage { @@ -240,25 +260,24 @@ struct CCVKGPUShaderStage { String source; VkShaderModule vkShader = VK_NULL_HANDLE; }; -using CCVKGPUShaderStageList = vector; class CCVKGPUShader final : public Object { public: - String name; - AttributeList attributes; - UniformBlockList blocks; - UniformSamplerList samplers; - CCVKGPUShaderStageList gpuStages; + String name; + AttributeList attributes; + UniformBlockList blocks; + UniformSamplerList samplers; + vector gpuStages; }; class CCVKGPUInputAssembler final : public Object { public: - AttributeList attributes; - CCVKGPUBufferList gpuVertexBuffers; - CCVKGPUBuffer * gpuIndexBuffer = nullptr; - CCVKGPUBuffer * gpuIndirectBuffer = nullptr; - vector vertexBuffers; - vector vertexBufferOffsets; + AttributeList attributes; + vector gpuVertexBuffers; + CCVKGPUBufferView * gpuIndexBuffer = nullptr; + CCVKGPUBufferView * gpuIndirectBuffer = nullptr; + vector vertexBuffers; + vector vertexBufferOffsets; }; union CCVKDescriptorInfo { @@ -273,12 +292,11 @@ struct CCVKGPUDescriptor { CCVKGPUTextureView * gpuTextureView = nullptr; CCVKGPUSampler * gpuSampler = nullptr; }; -using CCVKGPUDescriptorList = vector; class CCVKGPUDescriptorSetLayout; class CCVKGPUDescriptorSet final : public Object { public: - CCVKGPUDescriptorList gpuDescriptors; + vector gpuDescriptors; // references CCVKGPUDescriptorSetLayout *gpuLayout = nullptr; @@ -293,11 +311,9 @@ public: uint layoutID = 0U; }; -using CCVKGPUDescriptorSetLayoutList = vector; - class CCVKGPUPipelineLayout final : public Object { public: - CCVKGPUDescriptorSetLayoutList setLayouts; + vector setLayouts; VkPipelineLayout vkPipelineLayout = VK_NULL_HANDLE; @@ -346,20 +362,23 @@ class CCVKGPUCommandBufferPool; class CCVKGPUDescriptorSetPool; class CCVKGPUDevice final : public Object { public: - VkDevice vkDevice = VK_NULL_HANDLE; + VkDevice vkDevice{VK_NULL_HANDLE}; vector layers; vector extensions; - VmaAllocator memoryAllocator = VK_NULL_HANDLE; - VkPipelineCache vkPipelineCache = VK_NULL_HANDLE; - uint minorVersion = 0U; + VmaAllocator memoryAllocator{VK_NULL_HANDLE}; + VkPipelineCache vkPipelineCache{VK_NULL_HANDLE}; + uint minorVersion{0U}; - uint curBackBufferIndex = 0U; - uint backBufferCount = 3U; + VkFormat depthFormat{VK_FORMAT_UNDEFINED}; + VkFormat depthStencilFormat{VK_FORMAT_UNDEFINED}; - bool useDescriptorUpdateTemplate = false; - bool useMultiDrawIndirect = false; + uint curBackBufferIndex{0U}; + uint backBufferCount{3U}; - PFN_vkCreateRenderPass2 createRenderPass2 = nullptr; + bool useDescriptorUpdateTemplate{false}; + bool useMultiDrawIndirect{false}; + + PFN_vkCreateRenderPass2 createRenderPass2{nullptr}; // for default backup usages CCVKGPUSampler defaultSampler; @@ -367,7 +386,7 @@ public: CCVKGPUTextureView defaultTextureView; CCVKGPUBuffer defaultBuffer; - CCVKGPUSwapchain *swapchain = nullptr; // reference + unordered_set swapchains; CCVKGPUCommandBufferPool *getCommandBufferPool(); CCVKGPUDescriptorSetPool *getDescriptorSetPool(uint layoutID); @@ -936,13 +955,12 @@ public: } } // for resize events - void update(const CCVKGPUBuffer *buffer, VkDeviceSize oldStartOffset) { + void update(const CCVKGPUBuffer *buffer) { for (const auto &it : _buffers) { if (it.first->gpuBuffer != buffer) continue; const auto &info = it.second; for (uint i = 0U; i < info.descriptors.size(); i++) { - info.descriptors[i]->buffer = buffer->vkBuffer; - info.descriptors[i]->offset += buffer->startOffset - oldStartOffset; + doUpdate(it.first, info.descriptors[i]); } for (const auto *set : info.sets) { _descriptorSetHub->record(set); @@ -990,10 +1008,9 @@ public: private: void doUpdate(const CCVKGPUBufferView *buffer, VkDescriptorBufferInfo *descriptor) { - VkDeviceSize instanceOffset = _bufferInstanceIndices[descriptor] * buffer->gpuBuffer->instanceSize; - descriptor->buffer = buffer->gpuBuffer->vkBuffer; - descriptor->offset = buffer->gpuBuffer->startOffset + instanceOffset + buffer->offset; - descriptor->range = buffer->range; + descriptor->buffer = buffer->gpuBuffer->vkBuffer; + descriptor->offset = buffer->getStartOffset(_bufferInstanceIndices[descriptor]); + descriptor->range = buffer->range; } static void doUpdate(const CCVKGPUTextureView *texture, VkDescriptorImageInfo *descriptor) { @@ -1034,6 +1051,41 @@ public: _resources.resize(16); } + void collect(CCVKGPUTexture *gpuTexture) { + if (_resources.size() <= _count) { + _resources.resize(_count * 2); + } + if (gpuTexture->swapchain) { + if (GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].hasDepth) { + for (uint32_t i = 0; i < gpuTexture->swapchainVkImages.size(); ++i) { + vmaDestroyImage(_device->memoryAllocator, gpuTexture->swapchainVkImages[i], gpuTexture->swapchainVmaAllocations[i]); + } + gpuTexture->swapchainVkImages.clear(); + gpuTexture->swapchainVmaAllocations.clear(); + } + } else { + Resource &res = _resources[_count++]; + res.type = RecycledType::TEXTURE; + res.image = {gpuTexture->vkImage, gpuTexture->vmaAllocation}; + } + } + + void collect(CCVKGPUTextureView *gpuTextureView) { + if (_resources.size() <= _count) { + _resources.resize(_count * 2); + } + if (gpuTextureView->gpuTexture->swapchain) { + for (VkImageView swapchainVkImageView : gpuTextureView->swapchainVkImageViews) { + vkDestroyImageView(_device->vkDevice, swapchainVkImageView, nullptr); + } + gpuTextureView->swapchainVkImageViews.clear(); + } else { + Resource &res = _resources[_count++]; + res.type = RecycledType::TEXTURE_VIEW; + res.vkImageView = gpuTextureView->vkImageView; + } + } + #define DEFINE_RECYCLE_BIN_COLLECT_FN(_type, typeValue, expr) \ void collect(_type *gpuRes) { /* NOLINT(bugprone-macro-parentheses) N/A */ \ if (_resources.size() <= _count) { \ @@ -1045,8 +1097,6 @@ public: } DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUBuffer, RecycledType::BUFFER, (res.buffer = {gpuRes->vkBuffer, gpuRes->vmaAllocation})) - DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUTexture, RecycledType::TEXTURE, (res.image = {gpuRes->vkImage, gpuRes->vmaAllocation})) - DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUTextureView, RecycledType::TEXTURE_VIEW, res.vkImageView = gpuRes->vkImageView) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPURenderPass, RecycledType::RENDER_PASS, res.gpuRenderPass = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUFramebuffer, RecycledType::FRAMEBUFFER, res.gpuFramebuffer = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUSampler, RecycledType::SAMPLER, res.gpuSampler = gpuRes) @@ -1112,8 +1162,11 @@ public: CCVKGPUTransportHub(CCVKGPUDevice *device, CCVKGPUQueue *queue) : _device(device), _queue(queue) { - _cmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - _cmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; + _earlyCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + _earlyCmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; + + _lateCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + _lateCmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; VkFenceCreateInfo createInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; VK_CHECK(vkCreateFence(_device->vkDevice, &createInfo, nullptr, &_fence)); @@ -1126,51 +1179,46 @@ public: } } - void link(CCVKGPUQueue *queue) { - _queue = queue; + bool empty(bool late) const { + const CCVKGPUCommandBuffer *cmdBuff = late ? &_lateCmdBuff : &_earlyCmdBuff; - _cmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - _cmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; - - VkFenceCreateInfo createInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; - VK_CHECK(vkCreateFence(_device->vkDevice, &createInfo, nullptr, &_fence)); - } - - bool empty() const { - return !_cmdBuff.vkCommandBuffer; + return !cmdBuff->vkCommandBuffer; } template - void checkIn(const TFunc &record, bool immediateSubmission = false) { + void checkIn(const TFunc &record, bool immediateSubmission = false, bool late = false) { CCVKGPUCommandBufferPool *commandBufferPool = _device->getCommandBufferPool(); + CCVKGPUCommandBuffer * cmdBuff = late ? &_lateCmdBuff : &_earlyCmdBuff; - if (!_cmdBuff.vkCommandBuffer) { - commandBufferPool->request(&_cmdBuff); + if (!cmdBuff->vkCommandBuffer) { + commandBufferPool->request(cmdBuff); VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - VK_CHECK(vkBeginCommandBuffer(_cmdBuff.vkCommandBuffer, &beginInfo)); + VK_CHECK(vkBeginCommandBuffer(cmdBuff->vkCommandBuffer, &beginInfo)); } - record(&_cmdBuff); + record(cmdBuff); if (immediateSubmission) { - VK_CHECK(vkEndCommandBuffer(_cmdBuff.vkCommandBuffer)); + VK_CHECK(vkEndCommandBuffer(cmdBuff->vkCommandBuffer)); VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &_cmdBuff.vkCommandBuffer; + submitInfo.pCommandBuffers = &cmdBuff->vkCommandBuffer; VK_CHECK(vkQueueSubmit(_queue->vkQueue, 1, &submitInfo, _fence)); VK_CHECK(vkWaitForFences(_device->vkDevice, 1, &_fence, VK_TRUE, DEFAULT_TIMEOUT)); vkResetFences(_device->vkDevice, 1, &_fence); - commandBufferPool->yield(&_cmdBuff); - _cmdBuff.vkCommandBuffer = VK_NULL_HANDLE; + commandBufferPool->yield(cmdBuff); + cmdBuff->vkCommandBuffer = VK_NULL_HANDLE; } } - VkCommandBuffer packageForFlight() { - VkCommandBuffer vkCommandBuffer = _cmdBuff.vkCommandBuffer; + VkCommandBuffer packageForFlight(bool late) { + CCVKGPUCommandBuffer *cmdBuff = late ? &_lateCmdBuff : &_earlyCmdBuff; + + VkCommandBuffer vkCommandBuffer = cmdBuff->vkCommandBuffer; if (vkCommandBuffer) { VK_CHECK(vkEndCommandBuffer(vkCommandBuffer)); - _device->getCommandBufferPool()->yield(&_cmdBuff); + _device->getCommandBufferPool()->yield(cmdBuff); } return vkCommandBuffer; } @@ -1179,7 +1227,8 @@ private: CCVKGPUDevice *_device = nullptr; CCVKGPUQueue * _queue = nullptr; - CCVKGPUCommandBuffer _cmdBuff; + CCVKGPUCommandBuffer _earlyCmdBuff; + CCVKGPUCommandBuffer _lateCmdBuff; VkFence _fence = VK_NULL_HANDLE; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp b/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp index dfb3045550..676a767db0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp @@ -33,7 +33,9 @@ namespace cc { namespace gfx { -CCVKInputAssembler::CCVKInputAssembler() = default; +CCVKInputAssembler::CCVKInputAssembler() { + _typedID = generateObjectID(); +} CCVKInputAssembler::~CCVKInputAssembler() { destroy(); @@ -48,23 +50,24 @@ void CCVKInputAssembler::doInit(const InputAssemblerInfo &info) { for (size_t i = 0U; i < vbCount; ++i) { auto *vb = static_cast(_vertexBuffers[i]); - _gpuInputAssembler->gpuVertexBuffers[i] = vb->gpuBuffer(); + _gpuInputAssembler->gpuVertexBuffers[i] = vb->gpuBufferView(); } if (info.indexBuffer) { - _gpuInputAssembler->gpuIndexBuffer = static_cast(info.indexBuffer)->gpuBuffer(); + _gpuInputAssembler->gpuIndexBuffer = static_cast(info.indexBuffer)->gpuBufferView(); } if (info.indirectBuffer) { - _gpuInputAssembler->gpuIndirectBuffer = static_cast(info.indirectBuffer)->gpuBuffer(); + _gpuInputAssembler->gpuIndirectBuffer = static_cast(info.indirectBuffer)->gpuBufferView(); } _gpuInputAssembler->vertexBuffers.resize(vbCount); _gpuInputAssembler->vertexBufferOffsets.resize(vbCount); + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); for (size_t i = 0U; i < vbCount; i++) { - _gpuInputAssembler->vertexBuffers[i] = _gpuInputAssembler->gpuVertexBuffers[i]->vkBuffer; - _gpuInputAssembler->vertexBufferOffsets[i] = _gpuInputAssembler->gpuVertexBuffers[i]->startOffset; + _gpuInputAssembler->vertexBuffers[i] = _gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; + _gpuInputAssembler->vertexBufferOffsets[i] = _gpuInputAssembler->gpuVertexBuffers[i]->getStartOffset(gpuDevice->curBackBufferIndex); } } diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp b/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp index c5a12aa904..d6bc13353d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp @@ -33,7 +33,9 @@ namespace cc { namespace gfx { -CCVKPipelineLayout::CCVKPipelineLayout() = default; +CCVKPipelineLayout::CCVKPipelineLayout() { + _typedID = generateObjectID(); +} CCVKPipelineLayout::~CCVKPipelineLayout() { destroy(); @@ -42,10 +44,10 @@ CCVKPipelineLayout::~CCVKPipelineLayout() { void CCVKPipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { _gpuPipelineLayout = CC_NEW(CCVKGPUPipelineLayout); - int offset = 0U; + uint32_t offset = 0U; for (auto *setLayout : _setLayouts) { CCVKGPUDescriptorSetLayout *gpuSetLayout = static_cast(setLayout)->gpuDescriptorSetLayout(); - size_t dynamicCount = gpuSetLayout->dynamicBindings.size(); + uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); _gpuPipelineLayout->dynamicOffsetOffsets.push_back(offset); _gpuPipelineLayout->setLayouts.push_back(gpuSetLayout); offset += dynamicCount; diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp b/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp index d47b63d607..ff7d1bca04 100644 --- a/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp @@ -35,7 +35,9 @@ namespace cc { namespace gfx { -CCVKPipelineState::CCVKPipelineState() = default; +CCVKPipelineState::CCVKPipelineState() { + _typedID = generateObjectID(); +} CCVKPipelineState::~CCVKPipelineState() { destroy(); diff --git a/native/cocos/renderer/gfx-vulkan/VKQueue.cpp b/native/cocos/renderer/gfx-vulkan/VKQueue.cpp index d0488bddf4..a998f25966 100644 --- a/native/cocos/renderer/gfx-vulkan/VKQueue.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKQueue.cpp @@ -29,11 +29,14 @@ #include "VKCommands.h" #include "VKDevice.h" #include "VKQueue.h" +#include "vulkan/vulkan_core.h" namespace cc { namespace gfx { -CCVKQueue::CCVKQueue() = default; +CCVKQueue::CCVKQueue() { + _typedID = generateObjectID(); +} CCVKQueue::~CCVKQueue() { destroy(); @@ -62,14 +65,14 @@ void CCVKQueue::submit(CommandBuffer *const *cmdBuffs, uint count) { #endif device->gpuBufferHub()->flush(device->gpuTransportHub()); - if (!device->gpuTransportHub()->empty()) { - _gpuQueue->commandBuffers.push(device->gpuTransportHub()->packageForFlight()); + if (!device->gpuTransportHub()->empty(false)) { + _gpuQueue->commandBuffers.push_back(device->gpuTransportHub()->packageForFlight(false)); } for (uint i = 0U; i < count; ++i) { auto *cmdBuff = static_cast(cmdBuffs[i]); if (!cmdBuff->_pendingQueue.empty()) { - _gpuQueue->commandBuffers.push(cmdBuff->_pendingQueue.front()); + _gpuQueue->commandBuffers.push_back(cmdBuff->_pendingQueue.front()); cmdBuff->_pendingQueue.pop(); _numDrawCalls += cmdBuff->_numDrawCalls; @@ -78,20 +81,27 @@ void CCVKQueue::submit(CommandBuffer *const *cmdBuffs, uint count) { } } + if (!device->gpuTransportHub()->empty(true)) { + _gpuQueue->commandBuffers.push_back(device->gpuTransportHub()->packageForFlight(true)); + } + + size_t waitSemaphoreCount = _gpuQueue->lastSignaledSemaphores.size(); + VkSemaphore signal = waitSemaphoreCount ? device->gpuSemaphorePool()->alloc() : VK_NULL_HANDLE; + _gpuQueue->submitStageMasks.resize(waitSemaphoreCount, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submitInfo.waitSemaphoreCount = _gpuQueue->nextWaitSemaphore ? 1 : 0; - submitInfo.pWaitSemaphores = &_gpuQueue->nextWaitSemaphore; - submitInfo.pWaitDstStageMask = &_gpuQueue->submitStageMask; - submitInfo.commandBufferCount = _gpuQueue->commandBuffers.size(); + submitInfo.waitSemaphoreCount = utils::toUint(waitSemaphoreCount); + submitInfo.pWaitSemaphores = _gpuQueue->lastSignaledSemaphores.data(); + submitInfo.pWaitDstStageMask = _gpuQueue->submitStageMasks.data(); + submitInfo.commandBufferCount = utils::toUint(_gpuQueue->commandBuffers.size()); submitInfo.pCommandBuffers = &_gpuQueue->commandBuffers[0]; - submitInfo.signalSemaphoreCount = _gpuQueue->nextSignalSemaphore ? 1 : 0; - submitInfo.pSignalSemaphores = &_gpuQueue->nextSignalSemaphore; + submitInfo.signalSemaphoreCount = waitSemaphoreCount ? 1 : 0; + submitInfo.pSignalSemaphores = &signal; VkFence vkFence = device->gpuFencePool()->alloc(); VK_CHECK(vkQueueSubmit(_gpuQueue->vkQueue, 1, &submitInfo, vkFence)); - _gpuQueue->nextWaitSemaphore = _gpuQueue->nextSignalSemaphore; - _gpuQueue->nextSignalSemaphore = device->gpuSemaphorePool()->alloc(); + _gpuQueue->lastSignaledSemaphores.assign(1, signal); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp index c46d1de95a..af5f41d88c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp @@ -32,7 +32,9 @@ namespace cc { namespace gfx { -CCVKRenderPass::CCVKRenderPass() = default; +CCVKRenderPass::CCVKRenderPass() { + _typedID = generateObjectID(); +} CCVKRenderPass::~CCVKRenderPass() { destroy(); @@ -46,21 +48,14 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { _gpuRenderPass->dependencies = _dependencies; // assign a dummy subpass if not specified - // the depth stencil attachment is the default fallback - // when none are specified in subpass - const bool hasDepth = _depthStencilAttachment.format != Format::UNKNOWN; if (_gpuRenderPass->subpasses.empty()) { auto &subpass = _gpuRenderPass->subpasses.emplace_back(); subpass.colors.resize(_colorAttachments.size()); for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; } - subpass.depthStencil = hasDepth ? _colorAttachments.size() : INVALID_BINDING; - } else { - for (auto &subpass : _gpuRenderPass->subpasses) { - if (hasDepth && subpass.depthStencil == INVALID_BINDING) { - subpass.depthStencil = static_cast(_colorAttachments.size()); - } + if (_depthStencilAttachment.format != Format::UNKNOWN) { + subpass.depthStencil = utils::toUint(_colorAttachments.size()); } } diff --git a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h b/native/cocos/renderer/gfx-vulkan/VKSPIRV.h deleted file mode 100644 index 22503b678b..0000000000 --- a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "base/Log.h" -#include "gfx-base/GFXDef.h" - -#include "glslang/StandAlone/ResourceLimits.h" -#include "glslang/Public/ShaderLang.h" -#include "glslang/SPIRV/GlslangToSpv.h" - -namespace cc { -namespace gfx { - -inline EShLanguage getShaderStage(ShaderStageFlagBit type) { - switch (type) { - case ShaderStageFlagBit::VERTEX: return EShLangVertex; - case ShaderStageFlagBit::CONTROL: return EShLangTessControl; - case ShaderStageFlagBit::EVALUATION: return EShLangTessEvaluation; - case ShaderStageFlagBit::GEOMETRY: return EShLangGeometry; - case ShaderStageFlagBit::FRAGMENT: return EShLangFragment; - case ShaderStageFlagBit::COMPUTE: return EShLangCompute; - default: { - CCASSERT(false, "Unsupported ShaderStageFlagBit, convert to EShLanguage failed."); - return EShLangVertex; - } - } -} - -inline glslang::EShTargetClientVersion getClientVersion(int vulkanMinorVersion) { - switch (vulkanMinorVersion) { - case 0: return glslang::EShTargetVulkan_1_0; - case 1: return glslang::EShTargetVulkan_1_1; - case 2: return glslang::EShTargetVulkan_1_2; - default: { - CCASSERT(false, "Unsupported vulkan version, convert to EShTargetClientVersion failed."); - return glslang::EShTargetVulkan_1_0; - } - } -} - -inline glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { - switch (vulkanMinorVersion) { - case 0: return glslang::EShTargetSpv_1_0; - case 1: return glslang::EShTargetSpv_1_3; - case 2: return glslang::EShTargetSpv_1_5; - default: { - CCASSERT(false, "Unsupported vulkan version, convert to EShTargetLanguageVersion failed."); - return glslang::EShTargetSpv_1_0; - } - } -} - -inline bool glslangInitialized = false; - -inline vector glsl2spirv(ShaderStageFlagBit type, const String &source, int vulkanMinorVersion = 0) { - if (!glslangInitialized) { - glslang::InitializeProcess(); - glslangInitialized = true; - } - - EShLanguage stage = getShaderStage(type); - const char * string = source.c_str(); - glslang::TShader shader(stage); - shader.setStrings(&string, 1); - - int clientInputSemanticsVersion = 100 + vulkanMinorVersion * 10; - glslang::EShTargetClientVersion clientVersion = getClientVersion(vulkanMinorVersion); - glslang::EShTargetLanguageVersion targetVersion = getTargetVersion(vulkanMinorVersion); - - shader.setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientVulkan, clientInputSemanticsVersion); - shader.setEnvClient(glslang::EShClientVulkan, clientVersion); - shader.setEnvTarget(glslang::EShTargetSpv, targetVersion); - - auto messages = static_cast(EShMsgSpvRules | EShMsgVulkanRules); - - if (!shader.parse(&glslang::DefaultTBuiltInResource, clientInputSemanticsVersion, false, messages)) { - CC_LOG_ERROR("GLSL Parsing Failed:\n%s\n%s", shader.getInfoLog(), shader.getInfoDebugLog()); - } - - glslang::TProgram program; - program.addShader(&shader); - - if (!program.link(messages)) { - CC_LOG_ERROR("GLSL Linking Failed:\n%s\n%s", program.getInfoLog(), program.getInfoDebugLog()); - } - - vector spirv; - spv::SpvBuildLogger logger; - glslang::SpvOptions spvOptions; - glslang::GlslangToSpv(*program.getIntermediate(stage), spirv, &logger, &spvOptions); - - return spirv; -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKShader.cpp b/native/cocos/renderer/gfx-vulkan/VKShader.cpp index 6272727634..fe47695c04 100644 --- a/native/cocos/renderer/gfx-vulkan/VKShader.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKShader.cpp @@ -32,18 +32,20 @@ namespace cc { namespace gfx { -CCVKShader::CCVKShader() = default; +CCVKShader::CCVKShader() { + _typedID = generateObjectID(); +} CCVKShader::~CCVKShader() { destroy(); } void CCVKShader::doInit(const ShaderInfo & /*info*/) { - _gpuShader = CC_NEW(CCVKGPUShader); - _gpuShader->name = _name; + _gpuShader = CC_NEW(CCVKGPUShader); + _gpuShader->name = _name; _gpuShader->attributes = _attributes; - _gpuShader->blocks = _blocks; - _gpuShader->samplers = _samplers; + _gpuShader->blocks = _blocks; + _gpuShader->samplers = _samplers; for (ShaderStage &stage : _stages) { _gpuShader->gpuStages.push_back({stage.stage, stage.source}); } diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp new file mode 100644 index 0000000000..b0c67d518a --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -0,0 +1,430 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "VKStd.h" + +#include "VKCommands.h" +#include "VKDevice.h" +#include "VKGPUObjects.h" +#include "VKQueue.h" +#include "VKRenderPass.h" +#include "VKSwapchain.h" +#include "VKTexture.h" +#include "VKUtils.h" + +namespace cc { +namespace gfx { + +CCVKSwapchain::CCVKSwapchain() { + _typedID = generateObjectID(); + _preRotationEnabled = ENABLE_PRE_ROTATION; +} + +CCVKSwapchain::~CCVKSwapchain() { + destroy(); +} + +void CCVKSwapchain::doInit(const SwapchainInfo & /*info*/) { + auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + _gpuSwapchain = CC_NEW(CCVKGPUSwapchain); + gpuDevice->swapchains.insert(_gpuSwapchain); + + createVkSurface(); + + ///////////////////// Parameter Selection ///////////////////// + + uint32_t queueFamilyPropertiesCount = utils::toUint(gpuContext->queueFamilyProperties.size()); + _gpuSwapchain->queueFamilyPresentables.resize(queueFamilyPropertiesCount); + for (uint32_t propertyIndex = 0U; propertyIndex < queueFamilyPropertiesCount; propertyIndex++) { + vkGetPhysicalDeviceSurfaceSupportKHR(gpuContext->physicalDevice, propertyIndex, + _gpuSwapchain->vkSurface, &_gpuSwapchain->queueFamilyPresentables[propertyIndex]); + } + + // find other possible queues if not presentable + auto *queue = static_cast(CCVKDevice::getInstance()->getQueue()); + if (!_gpuSwapchain->queueFamilyPresentables[queue->gpuQueue()->queueFamilyIndex]) { + auto &indices = queue->gpuQueue()->possibleQueueFamilyIndices; + indices.erase(std::remove_if(indices.begin(), indices.end(), [this](uint32_t i) { + return !_gpuSwapchain->queueFamilyPresentables[i]; + }), + indices.end()); + CCASSERT(!_gpuSwapchain->queueFamilyPresentables.empty(), "no presentable queue found!"); + cmdFuncCCVKGetDeviceQueue(CCVKDevice::getInstance(), queue->gpuQueue()); + } + + Format colorFmt = Format::BGRA8; + Format depthStencilFmt = Format::DEPTH_STENCIL; + + VkSurfaceCapabilitiesKHR surfaceCapabilities{}; + vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities); + + uint surfaceFormatCount = 0U; + VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, nullptr)); + vector surfaceFormats(surfaceFormatCount); + VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, surfaceFormats.data())); + + uint presentModeCount = 0U; + VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, nullptr)); + vector presentModes(presentModeCount); + VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, presentModes.data())); + + VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; + VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, + // there is no preferred format, so we assume VK_FORMAT_B8G8R8A8_UNORM + if ((surfaceFormatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { + colorFormat = VK_FORMAT_B8G8R8A8_UNORM; + colorSpace = surfaceFormats[0].colorSpace; + } else { + // iterate over the list of available surface format and + // check for the presence of VK_FORMAT_B8G8R8A8_UNORM + bool imageFormatFound = false; + for (VkSurfaceFormatKHR &surfaceFormat : surfaceFormats) { + if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { + colorFormat = surfaceFormat.format; + colorSpace = surfaceFormat.colorSpace; + imageFormatFound = true; + break; + } + } + + // in case VK_FORMAT_B8G8R8A8_UNORM is not available + // select the first available color format + if (!imageFormatFound) { + colorFormat = surfaceFormats[0].format; + colorSpace = surfaceFormats[0].colorSpace; + switch (colorFormat) { + case VK_FORMAT_R8G8B8A8_UNORM: colorFmt = Format::RGBA8; break; + case VK_FORMAT_R8G8B8A8_SRGB: colorFmt = Format::SRGB8_A8; break; + case VK_FORMAT_R5G6B5_UNORM_PACK16: colorFmt = Format::R5G6B5; break; + default: CCASSERT(0, "assumption broken: new default surface format"); break; + } + } + } + + // Select a present mode for the swapchain + + vector presentModePriorityList; + + switch (_vsyncMode) { + case VsyncMode::OFF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::ON: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::RELAXED: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_RELAXED_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::MAILBOX: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::HALF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; // no easy fallback + } + + VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; + + // UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo +#if !defined(VK_USE_PLATFORM_ANDROID_KHR) + for (VkPresentModeKHR presentMode : presentModePriorityList) { + if (std::find(presentModes.begin(), presentModes.end(), presentMode) != presentModes.end()) { + swapchainPresentMode = presentMode; + break; + } + } +#endif + + // Determine the number of images + // for now we assume triple buffer is universal + uint desiredNumberOfSwapchainImages = gpuDevice->backBufferCount; + CCASSERT(desiredNumberOfSwapchainImages <= surfaceCapabilities.maxImageCount && + desiredNumberOfSwapchainImages >= surfaceCapabilities.minImageCount, + "Swapchain image count assumption broken"); + + VkExtent2D imageExtent = {1U, 1U}; + VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + + // Find a supported composite alpha format (not all devices support alpha opaque) + VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + // Simply select the first composite alpha format available + vector compositeAlphaFlags = { + VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, + VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, + }; + for (VkCompositeAlphaFlagBitsKHR compositeAlphaFlag : compositeAlphaFlags) { + if (surfaceCapabilities.supportedCompositeAlpha & compositeAlphaFlag) { + compositeAlpha = compositeAlphaFlag; + break; + }; + } + VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + // Enable transfer source on swap chain images if supported + if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { + imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } + + // Enable transfer destination on swap chain images if supported + if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) { + imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + } + + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.minImageCount = desiredNumberOfSwapchainImages; + _gpuSwapchain->createInfo.imageFormat = colorFormat; + _gpuSwapchain->createInfo.imageColorSpace = colorSpace; + _gpuSwapchain->createInfo.imageExtent = imageExtent; + _gpuSwapchain->createInfo.imageUsage = imageUsage; + _gpuSwapchain->createInfo.imageArrayLayers = 1; + _gpuSwapchain->createInfo.preTransform = preTransform; + _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; + _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; + _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area + + ///////////////////// Texture Creation ///////////////////// + + _colorTexture = CC_NEW(CCVKTexture); + _depthStencilTexture = CC_NEW(CCVKTexture); + + SwapchainTextureInfo textureInfo; + textureInfo.swapchain = this; + textureInfo.format = colorFmt; + textureInfo.width = 1; + textureInfo.height = 1; + initTexture(textureInfo, _colorTexture); + + textureInfo.format = depthStencilFmt; + initTexture(textureInfo, _depthStencilTexture); + + checkSwapchainStatus(); +} + +void CCVKSwapchain::doDestroy() { + if (!_gpuSwapchain) return; + + CCVKDevice::getInstance()->waitAllFences(); + + CC_SAFE_DESTROY(_depthStencilTexture) + CC_SAFE_DESTROY(_colorTexture) + + auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + + destroySwapchain(gpuDevice); + + if (_gpuSwapchain->vkSurface != VK_NULL_HANDLE) { + vkDestroySurfaceKHR(gpuContext->vkInstance, _gpuSwapchain->vkSurface, nullptr); + _gpuSwapchain->vkSurface = VK_NULL_HANDLE; + } + + gpuDevice->swapchains.erase(_gpuSwapchain); + CC_SAFE_DELETE(_gpuSwapchain) +} + +void CCVKSwapchain::doResize(uint32_t /*width*/, uint32_t /*height*/, SurfaceTransform /*transform*/) { + checkSwapchainStatus(); +} + +bool CCVKSwapchain::checkSwapchainStatus() { + auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + + VkSurfaceCapabilitiesKHR surfaceCapabilities; + VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities)); + + uint newWidth = surfaceCapabilities.currentExtent.width; + uint newHeight = surfaceCapabilities.currentExtent.height; + + VkSurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform; +#ifdef DISABLE_PRE_TRANSFORM + preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; +#endif + + if (preTransform & TRANSFORMS_THAT_REQUIRE_FLIPPING) { + newHeight = surfaceCapabilities.currentExtent.width; + newWidth = surfaceCapabilities.currentExtent.height; + } + + if (_gpuSwapchain->createInfo.preTransform == preTransform && + _gpuSwapchain->createInfo.imageExtent.width == newWidth && + _gpuSwapchain->createInfo.imageExtent.height == newHeight && _gpuSwapchain->lastPresentResult == VK_SUCCESS) { + return true; + } + + if (newWidth == static_cast(-1)) { + _gpuSwapchain->createInfo.imageExtent.width = _colorTexture->getWidth(); + _gpuSwapchain->createInfo.imageExtent.height = _colorTexture->getHeight(); + } else { + _gpuSwapchain->createInfo.imageExtent.width = newWidth; + _gpuSwapchain->createInfo.imageExtent.height = newHeight; + } + + if (newWidth == 0 || newHeight == 0) { + _gpuSwapchain->lastPresentResult = VK_NOT_READY; + return false; + } + + _transform = mapSurfaceTransform(preTransform); + _gpuSwapchain->createInfo.preTransform = preTransform; + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.oldSwapchain = _gpuSwapchain->vkSwapchain; + + CC_LOG_INFO("Resizing surface: %dx%d, surface rotation: %d degrees", newWidth, newHeight, (uint)_transform * 90); + + CCVKDevice::getInstance()->waitAllFences(); + + VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; + VK_CHECK(vkCreateSwapchainKHR(gpuDevice->vkDevice, &_gpuSwapchain->createInfo, nullptr, &vkSwapchain)); + + destroySwapchain(gpuDevice); + + gpuDevice->curBackBufferIndex = 0; + _gpuSwapchain->curImageIndex = 0; + _gpuSwapchain->vkSwapchain = vkSwapchain; + + uint imageCount; + VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, nullptr)); + _gpuSwapchain->swapchainImages.resize(imageCount); + VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, _gpuSwapchain->swapchainImages.data())); + + CCASSERT(imageCount == _gpuSwapchain->createInfo.minImageCount, "swapchain image count assumption is broken"); + + // should skip size check, since the old swapchain has already been destroyed + static_cast(_colorTexture)->_info.width = 0; + static_cast(_depthStencilTexture)->_info.width = 0; + _colorTexture->resize(newWidth, newHeight); + _depthStencilTexture->resize(newWidth, newHeight); + + bool hasStencil = GFX_FORMAT_INFOS[toNumber(_depthStencilTexture->getFormat())].hasStencil; + vector barriers(imageCount * 2, VkImageMemoryBarrier{}); + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + ThsvsImageBarrier tempBarrier{}; + tempBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + tempBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + tempBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; + tempBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; + VkPipelineStageFlags tempSrcStageMask = 0; + VkPipelineStageFlags tempDstStageMask = 0; + auto * colorGPUTexture = static_cast(_colorTexture)->gpuTexture(); + auto * depthStencilGPUTexture = static_cast(_depthStencilTexture)->gpuTexture(); + for (uint i = 0U; i < imageCount; i++) { + tempBarrier.nextAccessCount = 1; + tempBarrier.pNextAccesses = &THSVS_ACCESS_TYPES[toNumber(AccessType::PRESENT)]; + tempBarrier.image = _gpuSwapchain->swapchainImages[i]; + tempBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[i]); + srcStageMask |= tempSrcStageMask; + dstStageMask |= tempDstStageMask; + + tempBarrier.nextAccessCount = 1; + tempBarrier.pNextAccesses = &THSVS_ACCESS_TYPES[toNumber(AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE)]; + tempBarrier.image = depthStencilGPUTexture->swapchainVkImages[i]; + tempBarrier.subresourceRange.aspectMask = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[imageCount + i]); + srcStageMask |= tempSrcStageMask; + dstStageMask |= tempDstStageMask; + } + CCVKDevice::getInstance()->gpuTransportHub()->checkIn( + [&](const CCVKGPUCommandBuffer *gpuCommandBuffer) { + vkCmdPipelineBarrier(gpuCommandBuffer->vkCommandBuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, imageCount, barriers.data()); + }, + true); // submit immediately + + colorGPUTexture->currentAccessTypes.assign(1, THSVS_ACCESS_PRESENT); + depthStencilGPUTexture->currentAccessTypes.assign(1, THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ); + + for (auto &it : _gpuSwapchain->vkSwapchainFramebufferListMap) { + cmdFuncCCVKCreateFramebuffer(CCVKDevice::getInstance(), it.first); + } + + _gpuSwapchain->lastPresentResult = VK_SUCCESS; + + return true; +} + +void CCVKSwapchain::destroySwapchain(const CCVKGPUDevice *gpuDevice) { + if (_gpuSwapchain->vkSwapchain != VK_NULL_HANDLE) { + for (auto &it : _gpuSwapchain->vkSwapchainFramebufferListMap) { + FramebufferList &list = it.second; + for (VkFramebuffer framebuffer : list) { + vkDestroyFramebuffer(gpuDevice->vkDevice, framebuffer, nullptr); + } + list.clear(); + } + + _gpuSwapchain->swapchainImages.clear(); + + vkDestroySwapchainKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, nullptr); + _gpuSwapchain->vkSwapchain = VK_NULL_HANDLE; + } +} + +void CCVKSwapchain::doDestroySurface() { + if (!_gpuSwapchain || _gpuSwapchain->vkSurface == VK_NULL_HANDLE) return; + const auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + + CCVKDevice::getInstance()->waitAllFences(); + destroySwapchain(gpuDevice); + _gpuSwapchain->lastPresentResult = VK_NOT_READY; + + vkDestroySurfaceKHR(gpuContext->vkInstance, _gpuSwapchain->vkSurface, nullptr); + _gpuSwapchain->vkSurface = VK_NULL_HANDLE; +} + +void CCVKSwapchain::doCreateSurface(void * /*windowHandle*/) { + if (!_gpuSwapchain || _gpuSwapchain->vkSurface != VK_NULL_HANDLE) return; + createVkSurface(); + checkSwapchainStatus(); +} + +void CCVKSwapchain::createVkSurface() { + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + +#if defined(VK_USE_PLATFORM_ANDROID_KHR) + VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR}; + surfaceCreateInfo.window = reinterpret_cast(_windowHandle); + VK_CHECK(vkCreateAndroidSurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); +#elif defined(VK_USE_PLATFORM_WIN32_KHR) + VkWin32SurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + surfaceCreateInfo.hinstance = static_cast(GetModuleHandle(0)); + surfaceCreateInfo.hwnd = reinterpret_cast(_windowHandle); + VK_CHECK(vkCreateWin32SurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); +#elif defined(VK_USE_PLATFORM_METAL_EXT) + VkMetalSurfaceCreateInfoEXT surfaceCreateInfo{VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT}; + surfaceCreateInfo.pLayer = reinterpret_cast(_windowHandle); + VK_CHECK(vkCreateMetalSurfaceEXT(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); +#elif defined(VK_USE_PLATFORM_WAYLAND_KHR) + VkWaylandSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR}; + surfaceCreateInfo.display = nullptr; // TODO + surfaceCreateInfo.surface = reinterpret_cast(_windowHandle); + VK_CHECK(vkCreateWaylandSurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); +#elif defined(VK_USE_PLATFORM_XCB_KHR) + VkXcbSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR}; + surfaceCreateInfo.connection = nullptr; // TODO + surfaceCreateInfo.window = static_cast(_windowHandle); + VK_CHECK(vkCreateXcbSurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); +#else + #pragma error Platform not supported +#endif +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.h b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h new file mode 100644 index 0000000000..cf1278e646 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "VKStd.h" +#include "gfx-base/GFXSwapchain.h" + +namespace cc { +namespace gfx { + +class CCVKDevice; +class CCVKGPUDevice; +class CCVKGPUSwapchain; +class CCVKGPUSwapchain; +class CCVKGPUSemaphorePool; + +class CC_VULKAN_API CCVKSwapchain final : public Swapchain { +public: + static constexpr bool ENABLE_PRE_ROTATION = true; + + CCVKSwapchain(); + ~CCVKSwapchain() override; + + inline CCVKGPUSwapchain *gpuSwapchain() { return _gpuSwapchain; } + + bool checkSwapchainStatus(); + +protected: + void doInit(const SwapchainInfo &info) override; + void doDestroy() override; + void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) override; + void doDestroySurface() override; + void doCreateSurface(void *windowHandle) override; + + void createVkSurface(); + + void destroySwapchain(const CCVKGPUDevice *gpuDevice); + + CCVKGPUSwapchain *_gpuSwapchain = nullptr; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index 000be9306b..97c6bf6fa6 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -29,11 +29,15 @@ #include "VKCommands.h" #include "VKDevice.h" #include "VKTexture.h" +#include "gfx-base/GFXDef.h" +#include "gfx-vulkan/VKSwapchain.h" namespace cc { namespace gfx { -CCVKTexture::CCVKTexture() = default; +CCVKTexture::CCVKTexture() { + _typedID = generateObjectID(); +} CCVKTexture::~CCVKTexture() { destroy(); @@ -41,17 +45,17 @@ CCVKTexture::~CCVKTexture() { void CCVKTexture::doInit(const TextureInfo & /*info*/) { _gpuTexture = CC_NEW(CCVKGPUTexture); - _gpuTexture->type = _type; - _gpuTexture->format = _format; - _gpuTexture->usage = _usage; - _gpuTexture->width = _width; - _gpuTexture->height = _height; - _gpuTexture->depth = _depth; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayers = _info.layerCount; + _gpuTexture->mipLevels = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; _gpuTexture->size = _size; - _gpuTexture->arrayLayers = _layerCount; - _gpuTexture->mipLevels = _levelCount; - _gpuTexture->samples = _samples; - _gpuTexture->flags = _flags; cmdFuncCCVKCreateTexture(CCVKDevice::getInstance(), _gpuTexture); @@ -72,12 +76,12 @@ void CCVKTexture::doInit(const TextureViewInfo &info) { void CCVKTexture::createTextureView() { _gpuTextureView->gpuTexture = _gpuTexture; - _gpuTextureView->type = _type; - _gpuTextureView->format = _format; - _gpuTextureView->baseLevel = _baseLevel; - _gpuTextureView->levelCount = _levelCount; - _gpuTextureView->baseLayer = _baseLayer; - _gpuTextureView->layerCount = _layerCount; + _gpuTextureView->type = _viewInfo.type; + _gpuTextureView->format = _viewInfo.format; + _gpuTextureView->baseLevel = _viewInfo.baseLevel; + _gpuTextureView->levelCount = _viewInfo.levelCount; + _gpuTextureView->baseLayer = _viewInfo.baseLayer; + _gpuTextureView->layerCount = _viewInfo.layerCount; cmdFuncCCVKCreateTextureView(CCVKDevice::getInstance(), _gpuTextureView); } @@ -103,6 +107,8 @@ void CCVKTexture::doDestroy() { } void CCVKTexture::doResize(uint width, uint height, uint size) { + if (!width || !height) return; + if (!_gpuTexture->memoryless) { CCVKDevice::getInstance()->getMemoryStatus().textureSize -= _size; } @@ -122,5 +128,34 @@ void CCVKTexture::doResize(uint width, uint height, uint size) { cmdFuncCCVKCreateTextureView(CCVKDevice::getInstance(), _gpuTextureView); } +///////////////////////////// Swapchain Specific ///////////////////////////// + +void CCVKTexture::doInit(const SwapchainTextureInfo & /*info*/) { + _gpuTexture = CC_NEW(CCVKGPUTexture); + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; + _gpuTexture->arrayLayers = _info.layerCount; + _gpuTexture->mipLevels = _info.levelCount; + _gpuTexture->flags = _info.flags; + _gpuTexture->samples = _info.samples; + _gpuTexture->size = _size; + + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); + _gpuTexture->memoryless = true; + + _gpuTextureView = CC_NEW(CCVKGPUTextureView); + _gpuTextureView->gpuTexture = _gpuTexture; + _gpuTextureView->type = _viewInfo.type; + _gpuTextureView->format = _viewInfo.format; + _gpuTextureView->baseLevel = _viewInfo.baseLevel; + _gpuTextureView->levelCount = _viewInfo.levelCount; + _gpuTextureView->baseLayer = _viewInfo.baseLayer; + _gpuTextureView->layerCount = _viewInfo.layerCount; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.h b/native/cocos/renderer/gfx-vulkan/VKTexture.h index b628354e7d..929ac92252 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.h +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.h @@ -25,6 +25,7 @@ #pragma once +#include "VKStd.h" #include "gfx-base/GFXTexture.h" namespace cc { @@ -36,14 +37,17 @@ class CCVKGPUTextureView; class CC_VULKAN_API CCVKTexture final : public Texture { public: CCVKTexture(); - ~CCVKTexture(); + ~CCVKTexture() override; inline CCVKGPUTexture * gpuTexture() const { return _gpuTexture; } inline CCVKGPUTextureView *gpuTextureView() const { return _gpuTextureView; } protected: + friend class CCVKSwapchain; + void doInit(const TextureInfo &info) override; void doInit(const TextureViewInfo &info) override; + void doInit(const SwapchainTextureInfo &info) override; void doDestroy() override; void doResize(uint width, uint height, uint size) override; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index eb386faf0e..b40f572533 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -24,11 +24,12 @@ ****************************************************************************/ #include "VKUtils.h" +#include "VKGPUObjects.h" namespace cc { namespace gfx { -VkFormat mapVkFormat(Format format) { +VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice) { switch (format) { case Format::R8: return VK_FORMAT_R8_UNORM; case Format::R8SN: return VK_FORMAT_R8_SNORM; @@ -81,12 +82,8 @@ VkFormat mapVkFormat(Format format) { case Format::RGB10A2: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; case Format::RGB10A2UI: return VK_FORMAT_A2B10G10R10_UINT_PACK32; case Format::RGB9E5: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - case Format::D16: return VK_FORMAT_D16_UNORM; - case Format::D16S8: return VK_FORMAT_D16_UNORM_S8_UINT; - case Format::D24: return VK_FORMAT_X8_D24_UNORM_PACK32; - case Format::D24S8: return VK_FORMAT_D24_UNORM_S8_UINT; - case Format::D32F: return VK_FORMAT_D32_SFLOAT; - case Format::D32F_S8: return VK_FORMAT_D32_SFLOAT_S8_UINT; + case Format::DEPTH: return gpuDevice->depthFormat; + case Format::DEPTH_STENCIL: return gpuDevice->depthStencilFormat; case Format::BC1: return VK_FORMAT_BC1_RGB_UNORM_BLOCK; case Format::BC1_ALPHA: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; @@ -350,36 +347,6 @@ String mapVendorName(uint32_t vendorID) { return StringUtil::format("Unknown VendorID %d", vendorID); } -void mapDepthStencilBits(Format format, uint *pDepthBits, uint *pStencilBits) { - switch (format) { - case Format::D16: - *pDepthBits = 16; - *pStencilBits = 0; - break; - case Format::D16S8: - *pDepthBits = 16; - *pStencilBits = 8; - break; - case Format::D24: - *pDepthBits = 24; - *pStencilBits = 0; - break; - case Format::D24S8: - *pDepthBits = 24; - *pStencilBits = 8; - break; - case Format::D32F: - *pDepthBits = 32; - *pStencilBits = 0; - break; - case Format::D32F_S8: - *pDepthBits = 32; - *pStencilBits = 8; - break; - default: break; - } -} - const VkSurfaceTransformFlagsKHR TRANSFORMS_THAT_REQUIRE_FLIPPING = VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR; @@ -546,6 +513,17 @@ const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[] = { VK_STENCIL_FACE_FRONT_AND_BACK, }; +const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[] = { + VK_SAMPLE_COUNT_1_BIT, + VK_SAMPLE_COUNT_2_BIT, +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS + VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, +#else // desktop platforms + VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, +#endif + VK_SAMPLE_COUNT_16_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_2_BIT, +}; + const VkAccessFlags FULL_ACCESS_FLAGS = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 76e980b029..7cfcd796ce 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -50,7 +50,9 @@ namespace cc { namespace gfx { -extern VkFormat mapVkFormat(Format format); +class CCVKGPUDevice; + +extern VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice); extern VkAttachmentLoadOp mapVkLoadOp(LoadOp loadOp); extern VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); extern VkBufferUsageFlagBits mapVkBufferUsageFlagBits(BufferUsage usage); @@ -67,7 +69,6 @@ extern VkShaderStageFlagBits mapVkShaderStageFlagBits(ShaderStageFlagBit stage); extern VkShaderStageFlags mapVkShaderStageFlags(ShaderStageFlagBit stages); extern SurfaceTransform mapSurfaceTransform(VkSurfaceTransformFlagBitsKHR transform); extern String mapVendorName(uint32_t vendorID); -extern void mapDepthStencilBits(Format format, uint *pDepthBits, uint *pStencilBits); extern void fullPipelineBarrier(VkCommandBuffer cmdBuff); extern VkDeviceSize roundUp(VkDeviceSize numToRound, uint multiple); @@ -90,6 +91,7 @@ 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 VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[]; extern const VkAccessFlags FULL_ACCESS_FLAGS; } // namespace gfx diff --git a/native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.cpp b/native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.cpp similarity index 87% rename from native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.cpp rename to native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.cpp index 575e5d5dc6..288cb21d14 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.cpp @@ -23,21 +23,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "VKStd.h" - -#include "VKCommands.h" #include "VKGlobalBarrier.h" +#include "../VKCommands.h" namespace cc { namespace gfx { -CCVKGlobalBarrier::CCVKGlobalBarrier() = default; +CCVKGlobalBarrier::CCVKGlobalBarrier(const GlobalBarrierInfo &info) : GlobalBarrier(info) { + _typedID = generateObjectID(); -CCVKGlobalBarrier::~CCVKGlobalBarrier() { - CC_SAFE_DELETE(_gpuBarrier); -} - -void CCVKGlobalBarrier::doInit(const GlobalBarrierInfo &info) { _gpuBarrier = CC_NEW(CCVKGPUGlobalBarrier); _gpuBarrier->accessTypes.resize(info.prevAccesses.size() + info.nextAccesses.size()); @@ -49,13 +43,17 @@ void CCVKGlobalBarrier::doInit(const GlobalBarrierInfo &info) { _gpuBarrier->accessTypes[index++] = THSVS_ACCESS_TYPES[static_cast(type)]; } - _gpuBarrier->barrier.prevAccessCount = info.prevAccesses.size(); + _gpuBarrier->barrier.prevAccessCount = utils::toUint(info.prevAccesses.size()); _gpuBarrier->barrier.pPrevAccesses = _gpuBarrier->accessTypes.data(); - _gpuBarrier->barrier.nextAccessCount = info.nextAccesses.size(); + _gpuBarrier->barrier.nextAccessCount = utils::toUint(info.nextAccesses.size()); _gpuBarrier->barrier.pNextAccesses = _gpuBarrier->accessTypes.data() + info.prevAccesses.size(); thsvsGetVulkanMemoryBarrier(_gpuBarrier->barrier, &_gpuBarrier->srcStageMask, &_gpuBarrier->dstStageMask, &_gpuBarrier->vkBarrier); } +CCVKGlobalBarrier::~CCVKGlobalBarrier() { + CC_SAFE_DELETE(_gpuBarrier); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.h b/native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.h similarity index 83% rename from native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.h rename to native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.h index eb3afa19dc..cc6f0eabc4 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGlobalBarrier.h +++ b/native/cocos/renderer/gfx-vulkan/states/VKGlobalBarrier.h @@ -23,30 +23,26 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXVULKAN_GLOBAL_BARRIER_H_ -#define CC_GFXVULKAN_GLOBAL_BARRIER_H_ +#pragma once -#include "gfx-base/GFXGlobalBarrier.h" +#include "../VKStd.h" +#include "gfx-base/states/GFXGlobalBarrier.h" namespace cc { namespace gfx { class CCVKGPUGlobalBarrier; -class CC_DLL CCVKGlobalBarrier : public GlobalBarrier { +class CC_VULKAN_API CCVKGlobalBarrier : public GlobalBarrier { public: - CCVKGlobalBarrier(); - ~CCVKGlobalBarrier(); + explicit CCVKGlobalBarrier(const GlobalBarrierInfo &info); + ~CCVKGlobalBarrier() override; inline const CCVKGPUGlobalBarrier *gpuBarrier() const { return _gpuBarrier; } protected: - void doInit(const GlobalBarrierInfo &info) override; - CCVKGPUGlobalBarrier *_gpuBarrier = nullptr; }; } // namespace gfx } // namespace cc - -#endif // CC_GFXVULKAN_GLOBAL_BARRIER_H_ diff --git a/native/cocos/renderer/gfx-vulkan/VKSampler.cpp b/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp similarity index 71% rename from native/cocos/renderer/gfx-vulkan/VKSampler.cpp rename to native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp index d314afd3c6..580f4e9843 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSampler.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp @@ -23,38 +23,30 @@ THE SOFTWARE. ****************************************************************************/ -#include "VKStd.h" - -#include "VKCommands.h" -#include "VKDevice.h" #include "VKSampler.h" +#include "../VKCommands.h" +#include "../VKDevice.h" namespace cc { namespace gfx { -CCVKSampler::CCVKSampler() = default; +CCVKSampler::CCVKSampler(const SamplerInfo &info) : Sampler(info) { + _typedID = generateObjectID(); -CCVKSampler::~CCVKSampler() { - destroy(); -} - -void CCVKSampler::doInit(const SamplerInfo & /*info*/) { - _gpuSampler = CC_NEW(CCVKGPUSampler); - _gpuSampler->minFilter = _minFilter; - _gpuSampler->magFilter = _magFilter; - _gpuSampler->mipFilter = _mipFilter; - _gpuSampler->addressU = _addressU; - _gpuSampler->addressV = _addressV; - _gpuSampler->addressW = _addressW; - _gpuSampler->maxAnisotropy = _maxAnisotropy; - _gpuSampler->cmpFunc = _cmpFunc; - _gpuSampler->borderColor = _borderColor; - _gpuSampler->mipLODBias = _mipLODBias; + _gpuSampler = CC_NEW(CCVKGPUSampler); + _gpuSampler->minFilter = _info.minFilter; + _gpuSampler->magFilter = _info.magFilter; + _gpuSampler->mipFilter = _info.mipFilter; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; + _gpuSampler->maxAnisotropy = _info.maxAnisotropy; + _gpuSampler->cmpFunc = _info.cmpFunc; cmdFuncCCVKCreateSampler(CCVKDevice::getInstance(), _gpuSampler); } -void CCVKSampler::doDestroy() { +CCVKSampler::~CCVKSampler() { // NOLINT(bugprone-exception-escape) garbage collect may throw if (_gpuSampler) { CCVKDevice::getInstance()->gpuDescriptorHub()->disengage(_gpuSampler); CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuSampler); diff --git a/native/cocos/renderer/gfx-vulkan/VKSampler.h b/native/cocos/renderer/gfx-vulkan/states/VKSampler.h similarity index 91% rename from native/cocos/renderer/gfx-vulkan/VKSampler.h rename to native/cocos/renderer/gfx-vulkan/states/VKSampler.h index 143572b6c6..0262bc3a42 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSampler.h +++ b/native/cocos/renderer/gfx-vulkan/states/VKSampler.h @@ -25,7 +25,8 @@ #pragma once -#include "gfx-base/GFXSampler.h" +#include "../VKStd.h" +#include "gfx-base/states/GFXSampler.h" namespace cc { namespace gfx { @@ -34,15 +35,12 @@ class CCVKGPUSampler; class CC_VULKAN_API CCVKSampler final : public Sampler { public: - CCVKSampler(); - ~CCVKSampler(); + explicit CCVKSampler(const SamplerInfo &info); + ~CCVKSampler() override; inline CCVKGPUSampler *gpuSampler() const { return _gpuSampler; } protected: - void doInit(const SamplerInfo &info) override; - void doDestroy() override; - CCVKGPUSampler *_gpuSampler = nullptr; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKTextureBarrier.cpp b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp similarity index 73% rename from native/cocos/renderer/gfx-vulkan/VKTextureBarrier.cpp rename to native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp index bd8aa92de0..230e1eac5f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTextureBarrier.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp @@ -23,22 +23,16 @@ THE SOFTWARE. ****************************************************************************/ -#include "VKStd.h" - -#include "VKGPUObjects.h" -#include "VKQueue.h" #include "VKTextureBarrier.h" +#include "../VKGPUObjects.h" +#include "../VKQueue.h" namespace cc { namespace gfx { -CCVKTextureBarrier::CCVKTextureBarrier() = default; +CCVKTextureBarrier::CCVKTextureBarrier(const TextureBarrierInfo &info) : TextureBarrier(info) { + _typedID = generateObjectID(); -CCVKTextureBarrier::~CCVKTextureBarrier() { - CC_SAFE_DELETE(_gpuBarrier); -} - -void CCVKTextureBarrier::doInit(const TextureBarrierInfo &info) { _gpuBarrier = CC_NEW(CCVKGPUTextureBarrier); _gpuBarrier->accessTypes.resize(info.prevAccesses.size() + info.nextAccesses.size()); @@ -50,9 +44,9 @@ void CCVKTextureBarrier::doInit(const TextureBarrierInfo &info) { _gpuBarrier->accessTypes[index++] = THSVS_ACCESS_TYPES[static_cast(type)]; } - _gpuBarrier->barrier.prevAccessCount = info.prevAccesses.size(); + _gpuBarrier->barrier.prevAccessCount = utils::toUint(info.prevAccesses.size()); _gpuBarrier->barrier.pPrevAccesses = _gpuBarrier->accessTypes.data(); - _gpuBarrier->barrier.nextAccessCount = info.nextAccesses.size(); + _gpuBarrier->barrier.nextAccessCount = utils::toUint(info.nextAccesses.size()); _gpuBarrier->barrier.pNextAccesses = _gpuBarrier->accessTypes.data() + info.prevAccesses.size(); _gpuBarrier->barrier.prevLayout = _gpuBarrier->barrier.nextLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; @@ -61,15 +55,19 @@ void CCVKTextureBarrier::doInit(const TextureBarrierInfo &info) { _gpuBarrier->barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; _gpuBarrier->barrier.subresourceRange.baseArrayLayer = 0U; _gpuBarrier->barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - _gpuBarrier->barrier.srcQueueFamilyIndex = info.srcQueue - ? static_cast(info.srcQueue)->gpuQueue()->queueFamilyIndex - : VK_QUEUE_FAMILY_IGNORED; - _gpuBarrier->barrier.dstQueueFamilyIndex = info.dstQueue - ? static_cast(info.dstQueue)->gpuQueue()->queueFamilyIndex - : VK_QUEUE_FAMILY_IGNORED; + _gpuBarrier->barrier.srcQueueFamilyIndex = info.srcQueue + ? static_cast(info.srcQueue)->gpuQueue()->queueFamilyIndex + : VK_QUEUE_FAMILY_IGNORED; + _gpuBarrier->barrier.dstQueueFamilyIndex = info.dstQueue + ? static_cast(info.dstQueue)->gpuQueue()->queueFamilyIndex + : VK_QUEUE_FAMILY_IGNORED; thsvsGetVulkanImageMemoryBarrier(_gpuBarrier->barrier, &_gpuBarrier->srcStageMask, &_gpuBarrier->dstStageMask, &_gpuBarrier->vkBarrier); } +CCVKTextureBarrier::~CCVKTextureBarrier() { + CC_SAFE_DELETE(_gpuBarrier); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKTextureBarrier.h b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.h similarity index 83% rename from native/cocos/renderer/gfx-vulkan/VKTextureBarrier.h rename to native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.h index 846efadbff..d4f964b8f7 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTextureBarrier.h +++ b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.h @@ -23,30 +23,26 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CC_GFXVULKAN_TEXTURE_BARRIER_H_ -#define CC_GFXVULKAN_TEXTURE_BARRIER_H_ +#pragma once -#include "gfx-base/GFXTextureBarrier.h" +#include "../VKStd.h" +#include "gfx-base/states/GFXTextureBarrier.h" namespace cc { namespace gfx { class CCVKGPUTextureBarrier; -class CC_DLL CCVKTextureBarrier : public TextureBarrier { +class CC_VULKAN_API CCVKTextureBarrier : public TextureBarrier { public: - CCVKTextureBarrier(); - ~CCVKTextureBarrier(); + explicit CCVKTextureBarrier(const TextureBarrierInfo &info); + ~CCVKTextureBarrier() override; inline const CCVKGPUTextureBarrier *gpuBarrier() const { return _gpuBarrier; } protected: - void doInit(const TextureBarrierInfo &info) override; - CCVKGPUTextureBarrier *_gpuBarrier = nullptr; }; } // namespace gfx } // namespace cc - -#endif // CC_GFXVULKAN_TEXTURE_BARRIER_H_ diff --git a/native/cocos/renderer/pipeline/BatchedBuffer.cpp b/native/cocos/renderer/pipeline/BatchedBuffer.cpp index cbdf13a967..1549812309 100644 --- a/native/cocos/renderer/pipeline/BatchedBuffer.cpp +++ b/native/cocos/renderer/pipeline/BatchedBuffer.cpp @@ -151,7 +151,7 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s ++batch.mergeCount; batch.vbCount += vbCount; - auto prevCount = batch.ia->getVertexCount(); + auto prevCount = batch.ia->getDrawInfo().vertexCount; batch.ia->setVertexCount(prevCount + vbCount); return; } diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index 15ab5f51d1..c014930c1a 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -135,6 +135,9 @@ const gfx::UniformBlock UBOShadow::LAYOUT = { {"cc_matLightPlaneProj", gfx::Type::MAT4, 1}, {"cc_matLightView", gfx::Type::MAT4, 1}, {"cc_matLightViewProj", gfx::Type::MAT4, 1}, + {"cc_shadowInvProjDepthInfo", gfx::Type::FLOAT4, 1}, + {"cc_shadowProjDepthInfo", gfx::Type::FLOAT4, 1}, + {"cc_shadowProjInfo", gfx::Type::FLOAT4, 1}, {"cc_shadowNFLSInfo", gfx::Type::FLOAT4, 1}, {"cc_shadowWHPBInfo", gfx::Type::FLOAT4, 1}, {"cc_shadowLPNNInfo", gfx::Type::FLOAT4, 1}, @@ -275,86 +278,6 @@ const gfx::UniformSamplerTexture SHADOWMAP::LAYOUT = { 1, }; -const String SAMPLERGBUFFERALBEDOMAP::NAME = "cc_gbuffer_albedoMap"; -const gfx::DescriptorSetLayoutBinding SAMPLERGBUFFERALBEDOMAP::DESCRIPTOR = { - SAMPLERGBUFFERALBEDOMAP::BINDING, - gfx::DescriptorType::SAMPLER_TEXTURE, - 1, - gfx::ShaderStageFlagBit::FRAGMENT, - {}, -}; -const gfx::UniformSamplerTexture SAMPLERGBUFFERALBEDOMAP::LAYOUT = { - globalSet, - SAMPLERGBUFFERALBEDOMAP::BINDING, - SAMPLERGBUFFERALBEDOMAP::NAME, - gfx::Type::SAMPLER2D, - 1, -}; - -const String SAMPLERGBUFFERPOSITIONMAP::NAME = "cc_gbuffer_positionMap"; -const gfx::DescriptorSetLayoutBinding SAMPLERGBUFFERPOSITIONMAP::DESCRIPTOR = { - SAMPLERGBUFFERPOSITIONMAP::BINDING, - gfx::DescriptorType::SAMPLER_TEXTURE, - 1, - gfx::ShaderStageFlagBit::FRAGMENT, - {}, -}; -const gfx::UniformSamplerTexture SAMPLERGBUFFERPOSITIONMAP::LAYOUT = { - globalSet, - SAMPLERGBUFFERPOSITIONMAP::BINDING, - SAMPLERGBUFFERPOSITIONMAP::NAME, - gfx::Type::SAMPLER2D, - 1, -}; - -const String SAMPLERGBUFFERNORMALMAP::NAME = "cc_gbuffer_normalMap"; -const gfx::DescriptorSetLayoutBinding SAMPLERGBUFFERNORMALMAP::DESCRIPTOR = { - SAMPLERGBUFFERNORMALMAP::BINDING, - gfx::DescriptorType::SAMPLER_TEXTURE, - 1, - gfx::ShaderStageFlagBit::FRAGMENT, - {}, -}; -const gfx::UniformSamplerTexture SAMPLERGBUFFERNORMALMAP::LAYOUT = { - globalSet, - SAMPLERGBUFFERNORMALMAP::BINDING, - SAMPLERGBUFFERNORMALMAP::NAME, - gfx::Type::SAMPLER2D, - 1, -}; - -const String SAMPLERGBUFFEREMISSIVEMAP::NAME = "cc_gbuffer_emissiveMap"; -const gfx::DescriptorSetLayoutBinding SAMPLERGBUFFEREMISSIVEMAP::DESCRIPTOR = { - SAMPLERGBUFFEREMISSIVEMAP::BINDING, - gfx::DescriptorType::SAMPLER_TEXTURE, - 1, - gfx::ShaderStageFlagBit::FRAGMENT, - {}, -}; -const gfx::UniformSamplerTexture SAMPLERGBUFFEREMISSIVEMAP::LAYOUT = { - globalSet, - SAMPLERGBUFFEREMISSIVEMAP::BINDING, - SAMPLERGBUFFEREMISSIVEMAP::NAME, - gfx::Type::SAMPLER2D, - 1, -}; - -const String SAMPLERLIGHTINGRESULTMAP::NAME = "cc_lighting_resultMap"; -const gfx::DescriptorSetLayoutBinding SAMPLERLIGHTINGRESULTMAP::DESCRIPTOR = { - SAMPLERLIGHTINGRESULTMAP::BINDING, - gfx::DescriptorType::SAMPLER_TEXTURE, - 1, - gfx::ShaderStageFlagBit::FRAGMENT, - {}, -}; -const gfx::UniformSamplerTexture SAMPLERLIGHTINGRESULTMAP::LAYOUT = { - globalSet, - SAMPLERLIGHTINGRESULTMAP::BINDING, - SAMPLERLIGHTINGRESULTMAP::NAME, - gfx::Type::SAMPLER2D, - 1, -}; - const String ENVIRONMENT::NAME = "cc_environment"; const gfx::DescriptorSetLayoutBinding ENVIRONMENT::DESCRIPTOR = { ENVIRONMENT::BINDING, @@ -515,54 +438,6 @@ const gfx::UniformStorageImage REFLECTIONSTORAGE::LAYOUT = { 1, }; -uint SamplerLib::defaultSamplerHash{genSamplerHash(gfx::SamplerInfo())}; - -unordered_map SamplerLib::samplerCache{}; - -uint SamplerLib::genSamplerHash(const gfx::SamplerInfo &info) { - uint hash = 0; - hash |= static_cast(info.minFilter); - hash |= static_cast(info.magFilter) << 2; - hash |= static_cast(info.mipFilter) << 4; - hash |= static_cast(info.addressU) << 6; - hash |= static_cast(info.addressV) << 8; - hash |= static_cast(info.addressW) << 10; - hash |= static_cast(info.maxAnisotropy) << 12; - hash |= static_cast(info.cmpFunc) << 16; - hash |= static_cast(info.mipLODBias) << 28; - return hash; -} - -gfx::Sampler *SamplerLib::getSampler(uint hash) { - if (hash == 0) { - hash = defaultSamplerHash; - } - - if (samplerCache.count(hash)) { - return samplerCache[hash]; - } - - gfx::SamplerInfo info; - info.minFilter = static_cast(hash & 3); - info.magFilter = static_cast((hash >> 2) & 3); - info.mipFilter = static_cast((hash >> 4) & 3); - info.addressU = static_cast((hash >> 6) & 3); - info.addressV = static_cast((hash >> 8) & 3); - info.addressW = static_cast((hash >> 10) & 3); - info.maxAnisotropy = ((hash >> 12) & 15); - info.cmpFunc = static_cast((hash >> 16) & 15); - info.mipLODBias = static_cast((hash >> 28) & 15); - - return samplerCache[hash] = gfx::Device::getInstance()->createSampler(info); -} - -void SamplerLib::destroyAll() { - for (auto &pair : samplerCache) { - CC_SAFE_DESTROY(pair.second); - } - samplerCache.clear(); -} - uint skyboxFlag = static_cast(gfx::ClearFlagBit::STENCIL) << 1; uint nextPow2(uint val) { diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index 989e0b0ada..1723c97f9d 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -28,6 +28,7 @@ #include #include "base/Object.h" +#include "base/TypeDef.h" #include "base/Value.h" #include "renderer/gfx-base/GFXDef.h" #include "scene/Light.h" @@ -104,6 +105,7 @@ enum class RenderFlowType : uint8_t { POSTPROCESS, UI, }; +CC_ENUM_CONVERSION_OPERATOR(RenderFlowType) using RenderStageList = vector; using RenderFlowList = vector; @@ -114,6 +116,7 @@ enum class CC_DLL RenderPassStage { DEFAULT = 100, UI = 200, }; +CC_ENUM_CONVERSION_OPERATOR(RenderPassStage) struct CC_DLL InternalBindingDesc { gfx::DescriptorType type; @@ -139,11 +142,13 @@ enum class CC_DLL RenderPriority { MAX = 0xff, DEFAULT = 0x80, }; +CC_ENUM_CONVERSION_OPERATOR(RenderPriority) enum class CC_DLL RenderQueueSortMode { FRONT_TO_BACK, BACK_TO_FRONT, }; +CC_ENUM_CONVERSION_OPERATOR(RenderQueueSortMode) struct CC_DLL RenderQueueDesc { bool isTransparent = false; @@ -209,16 +214,12 @@ enum class CC_DLL PipelineGlobalBindings { UBO_SHADOW, SAMPLER_SHADOWMAP, - SAMPLER_ENVIRONMENT, // don't put this as the first sampler binding due to Mac GL driver issues: cubemap at texture unit 0 causes rendering issues + SAMPLER_ENVIRONMENT, SAMPLER_SPOT_LIGHTING_MAP, - SAMPLER_GBUFFER_ALBEDOMAP, - SAMPLER_GBUFFER_POSITIONMAP, - SAMPLER_GBUFFER_NORMALMAP, - SAMPLER_GBUFFER_EMISSIVEMAP, - SAMPLER_LIGHTING_RESULTMAP, COUNT, }; +CC_ENUM_CONVERSION_OPERATOR(PipelineGlobalBindings) extern CC_DLL int globalUBOCount; extern CC_DLL int globalSamplerCount; @@ -241,6 +242,7 @@ enum class CC_DLL ModelLocalBindings { COUNT, }; +CC_ENUM_CONVERSION_OPERATOR(ModelLocalBindings) extern CC_DLL int localUBOCount; extern CC_DLL int localSamplerCount; @@ -347,18 +349,21 @@ enum class CC_DLL ForwardStagePriority { FORWARD = 10, UI = 20 }; +CC_ENUM_CONVERSION_OPERATOR(ForwardStagePriority) enum class CC_DLL ForwardFlowPriority { SHADOW = 0, FORWARD = 1, UI = 10, }; +CC_ENUM_CONVERSION_OPERATOR(ForwardFlowPriority) enum class CC_DLL RenderFlowTag { SCENE, POSTPROCESS, UI, }; +CC_ENUM_CONVERSION_OPERATOR(RenderFlowTag) enum class CC_DLL DeferredStagePriority { GBUFFER = 10, @@ -367,12 +372,14 @@ enum class CC_DLL DeferredStagePriority { POSTPROCESS = 19, UI = 20 }; +CC_ENUM_CONVERSION_OPERATOR(DeferredStagePriority) enum class CC_DLL DeferredFlowPriority { - SHADOW = 0, - MAIN = 1, - UI = 10 + SHADOW = 0, + MAIN = 1, + UI = 10 }; +CC_ENUM_CONVERSION_OPERATOR(DeferredFlowPriority) struct CC_DLL UBOGlobal : public Object { static constexpr uint TIME_OFFSET = 0; @@ -430,19 +437,6 @@ struct CC_DLL UBOShadow : public Object { static const String NAME; }; -class CC_DLL SamplerLib : public Object { -public: - static gfx::Sampler *getSampler(uint hash); - static uint genSamplerHash(const gfx::SamplerInfo &info); - - static void destroyAll(); - -protected: - static uint defaultSamplerHash; - - static unordered_map samplerCache; -}; - struct CC_DLL DescriptorSetLayoutInfos { gfx::DescriptorSetLayoutBindingList bindings; unordered_map blocks; @@ -465,6 +459,7 @@ enum class LayerList : uint { DEFAULT = (1 << 30), ALL = 0xffffffff, }; +CC_ENUM_CONVERSION_OPERATOR(LayerList) const uint CAMERA_DEFAULT_MASK = ~static_cast(LayerList::UI_2D) & ~static_cast(LayerList::PROFILER); //constexpr CAMERA_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, @@ -483,41 +478,6 @@ struct CC_DLL SHADOWMAP : public Object { static const String NAME; }; -struct CC_DLL SAMPLERGBUFFERALBEDOMAP : public Object { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_ALBEDOMAP); - static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const String NAME; -}; - -struct CC_DLL SAMPLERGBUFFERPOSITIONMAP : public Object { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_POSITIONMAP); - static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const String NAME; -}; - -struct CC_DLL SAMPLERGBUFFERNORMALMAP : public Object { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_NORMALMAP); - static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const String NAME; -}; - -struct CC_DLL SAMPLERGBUFFEREMISSIVEMAP : public Object { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_EMISSIVEMAP); - static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const String NAME; -}; - -struct CC_DLL SAMPLERLIGHTINGRESULTMAP : public Object { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_LIGHTING_RESULTMAP); - static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const String NAME; -}; - struct CC_DLL ENVIRONMENT : public Object { static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_ENVIRONMENT); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; diff --git a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp index 5f5ee3c57c..1c961d169b 100644 --- a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp +++ b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp @@ -28,12 +28,7 @@ #include "Define.h" #include "RenderInstancedQueue.h" #include "forward/ForwardPipeline.h" -#include "gfx-base/GFXBuffer.h" -#include "gfx-base/GFXDescriptorSet.h" -#include "gfx-base/GFXDescriptorSetLayout.h" #include "gfx-base/GFXDevice.h" -#include "gfx-base/GFXSampler.h" -#include "gfx-base/GFXTexture.h" namespace cc { namespace pipeline { @@ -48,35 +43,23 @@ void GlobalDSManager::activate(gfx::Device *device, RenderPipeline *pipeline) { _device = device; _pipeline = pipeline; - const gfx::SamplerInfo linearInfo{ + _linearSampler = device->getSampler({ gfx::Filter::LINEAR, gfx::Filter::LINEAR, gfx::Filter::NONE, gfx::Address::CLAMP, gfx::Address::CLAMP, gfx::Address::CLAMP, - {}, - {}, - {}, - {}, - }; - const uint linearHash = SamplerLib::genSamplerHash(linearInfo); - _linearSampler = SamplerLib::getSampler(linearHash); + }); - const gfx::SamplerInfo pointInfo{ + _pointSampler = device->getSampler({ gfx::Filter::POINT, gfx::Filter::POINT, gfx::Filter::NONE, gfx::Address::CLAMP, gfx::Address::CLAMP, gfx::Address::CLAMP, - {}, - {}, - {}, - {}, - }; - const uint pointHash = SamplerLib::genSamplerHash(pointInfo); - _pointSampler = SamplerLib::getSampler(pointHash); + }); setDescriptorSetLayout(); if (_descriptorSetLayout) { @@ -185,12 +168,6 @@ void GlobalDSManager::setDescriptorSetLayout() { globalDescriptorSetLayout.samplers[SPOTLIGHTINGMAP::NAME] = SPOTLIGHTINGMAP::LAYOUT; globalDescriptorSetLayout.bindings[SPOTLIGHTINGMAP::BINDING] = SPOTLIGHTINGMAP::DESCRIPTOR; - INIT_GLOBAL_DESCSET_LAYOUT(SAMPLERGBUFFERALBEDOMAP); - INIT_GLOBAL_DESCSET_LAYOUT(SAMPLERGBUFFERPOSITIONMAP); - INIT_GLOBAL_DESCSET_LAYOUT(SAMPLERGBUFFEREMISSIVEMAP); - INIT_GLOBAL_DESCSET_LAYOUT(SAMPLERGBUFFERNORMALMAP); - INIT_GLOBAL_DESCSET_LAYOUT(SAMPLERLIGHTINGRESULTMAP); - localDescriptorSetLayout.bindings.resize(static_cast(ModelLocalBindings::COUNT)); localDescriptorSetLayout.blocks[UBOLocalBatched::NAME] = UBOLocalBatched::LAYOUT; localDescriptorSetLayout.bindings[UBOLocalBatched::BINDING] = UBOLocalBatched::DESCRIPTOR; diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index 6f3a05f3ea..7075e19bcd 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -125,7 +125,7 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su auto newSize = stride * INITIAL_CAPACITY; auto *vb = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, + gfx::MemoryUsageBit::DEVICE, static_cast(newSize), static_cast(stride), }); diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index 097a804986..2d1011a923 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -46,21 +46,21 @@ namespace pipeline { Mat4 matShadowViewProj; -void PipelineUBO::updateGlobalUBOView(const RenderPipeline * /*pipeline*/, std::array *bufferView) { +void PipelineUBO::updateGlobalUBOView(const scene::Camera *camera, std::array *bufferView) { auto *const root = scene::Root::instance; auto * device = gfx::Device::getInstance(); auto & uboGlobalView = *bufferView; - const auto shadingWidth = std::floor(device->getWidth()); - const auto shadingHeight = std::floor(device->getHeight()); + const auto shadingWidth = std::floor(camera->window->getWidth()); + const auto shadingHeight = std::floor(camera->window->getHeight()); // update UBOGlobal uboGlobalView[UBOGlobal::TIME_OFFSET + 0] = root->cumulativeTime; uboGlobalView[UBOGlobal::TIME_OFFSET + 1] = root->frameTime; uboGlobalView[UBOGlobal::TIME_OFFSET + 2] = static_cast(Application::getInstance()->getTotalFrames()); - uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 0] = static_cast(device->getWidth()); - uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 1] = static_cast(device->getHeight()); + uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 0] = static_cast(shadingWidth); + uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 1] = static_cast(shadingHeight); uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 2] = 1.0F / uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET]; uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 3] = 1.0F / uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 1]; @@ -84,8 +84,8 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out auto *device = gfx::Device::getInstance(); - const auto shadingWidth = std::floor(device->getWidth()); - const auto shadingHeight = std::floor(device->getHeight()); + const auto shadingWidth = std::floor(camera->window->getWidth()); + const auto shadingHeight = std::floor(camera->window->getHeight()); output[UBOCamera::SCREEN_SCALE_OFFSET + 0] = static_cast(camera->width / shadingWidth * shadingScale); output[UBOCamera::SCREEN_SCALE_OFFSET + 1] = static_cast(camera->height / shadingHeight * shadingScale); @@ -131,7 +131,7 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out output[UBOCamera::AMBIENT_GROUND_OFFSET + 2] = ambient->groundAlbedo.z; auto *const envmap = descriptorSet->getTexture(static_cast(PipelineGlobalBindings::SAMPLER_ENVIRONMENT)); if (envmap) { - output[UBOCamera::AMBIENT_GROUND_OFFSET + 3] = static_cast(envmap->getLevelCount()); + output[UBOCamera::AMBIENT_GROUND_OFFSET + 3] = static_cast(envmap->getViewInfo().levelCount); } memcpy(output + UBOCamera::MAT_VIEW_OFFSET, camera->matView.m, sizeof(cc::Mat4)); @@ -357,7 +357,7 @@ void PipelineUBO::activate(gfx::Device *device, RenderPipeline *pipeline) { auto *shadowUBO = _device->createBuffer({ gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, + gfx::MemoryUsageBit::DEVICE, UBOShadow::SIZE, UBOShadow::SIZE, gfx::BufferFlagBit::NONE, @@ -373,11 +373,11 @@ void PipelineUBO::destroy() { _ubos.clear(); } -void PipelineUBO::updateGlobalUBO() { +void PipelineUBO::updateGlobalUBO(const scene::Camera *camera) { auto *const globalDSManager = _pipeline->getGlobalDSManager(); auto *const ds = _pipeline->getDescriptorSet(); ds->update(); - PipelineUBO::updateGlobalUBOView(_pipeline, &_globalUBO); + PipelineUBO::updateGlobalUBOView(camera, &_globalUBO); ds->getBuffer(UBOGlobal::BINDING)->update(_globalUBO.data(), UBOGlobal::SIZE); globalDSManager->bindBuffer(UBOGlobal::BINDING, ds->getBuffer(UBOGlobal::BINDING)); diff --git a/native/cocos/renderer/pipeline/PipelineUBO.h b/native/cocos/renderer/pipeline/PipelineUBO.h index 4119e67b2a..f327241757 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.h +++ b/native/cocos/renderer/pipeline/PipelineUBO.h @@ -40,7 +40,7 @@ class RenderPipeline; class CC_DLL PipelineUBO : public Object { public: - static void updateGlobalUBOView(const RenderPipeline *pipeline, std::array *bufferView); + static void updateGlobalUBOView(const scene::Camera *camera, std::array *bufferView); static void updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera); static void updateShadowUBOView(const RenderPipeline *pipeline, std::array *bufferView, const scene::Camera *camera); static void updateShadowUBOLightView(const RenderPipeline *pipeline, std::array *bufferView, const scene::Light *light); @@ -50,7 +50,7 @@ public: ~PipelineUBO() override = default; void activate(gfx::Device *device, RenderPipeline *pipeline); void destroy(); - void updateGlobalUBO(); + void updateGlobalUBO(const scene::Camera *camera); void updateCameraUBO(const scene::Camera *camera); void updateMultiCameraUBO(const vector &cameras); void updateShadowUBO(const scene::Camera *camera); diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 8677156c60..d26b876634 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -31,20 +31,14 @@ #include "RenderAdditiveLightQueue.h" #include "Define.h" +#include "GlobalDescriptorSetManager.h" #include "RenderBatchedQueue.h" #include "RenderInstancedQueue.h" #include "SceneCulling.h" #include "forward/ForwardPipeline.h" -#include "gfx-base/GFXBuffer.h" -#include "gfx-base/GFXCommandBuffer.h" -#include "gfx-base/GFXDescriptorSet.h" #include "gfx-base/GFXDevice.h" -#include "gfx-base/GFXFramebuffer.h" -#include "gfx-base/GFXSampler.h" -#include "gfx-base/GFXTexture.h" #include "scene/RenderScene.h" #include "scene/Sphere.h" -#include "GlobalDescriptorSetManager.h" namespace cc { namespace pipeline { @@ -306,14 +300,14 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm } void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { - auto *const sceneData = _pipeline->getPipelineSceneData(); - auto * shadowInfo = sceneData->getSharedData()->shadow; - const auto *const scene = camera->scene; - auto * device = gfx::Device::getInstance(); - const bool hFTexture = supportsHalfFloatTexture(device); - const float linear = 0.0F; - const float packing = hFTexture ? 0.0F : 1.0F; - const scene::Light *mainLight = scene->getMainLight(); + auto *const sceneData = _pipeline->getPipelineSceneData(); + auto * shadowInfo = sceneData->getSharedData()->shadow; + const auto *const scene = camera->scene; + auto * device = gfx::Device::getInstance(); + const bool hFTexture = supportsHalfFloatTexture(device); + const float linear = 0.0F; + const float packing = hFTexture ? 0.0F : 1.0F; + const scene::Light *mainLight = scene->getMainLight(); for (uint i = 0; i < _validLights.size(); ++i) { const auto *light = _validLights[i]; @@ -351,7 +345,7 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam cc::Mat4 matShadowProj; cc::Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowProj); cc::Mat4 matShadowViewProj = matShadowProj; - cc::Mat4 matShadowInvProj = matShadowProj; + cc::Mat4 matShadowInvProj = matShadowProj; matShadowInvProj.inverse(); matShadowViewProj.multiply(matShadowView); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 9fdb95e87b..9eb7f91f22 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -24,6 +24,7 @@ ****************************************************************************/ #include "RenderPipeline.h" +#include "InstancedBuffer.h" #include "PipelineStateManager.h" #include "RenderFlow.h" #include "gfx-base/GFXCommandBuffer.h" @@ -31,7 +32,6 @@ #include "gfx-base/GFXDescriptorSetLayout.h" #include "gfx-base/GFXDevice.h" #include "gfx-base/GFXTexture.h" -#include "InstancedBuffer.h" namespace cc { namespace pipeline { @@ -63,7 +63,7 @@ bool RenderPipeline::initialize(const RenderPipelineInfo &info) { return true; } -bool RenderPipeline::activate() { +bool RenderPipeline::activate(gfx::Swapchain * /*swapchain*/) { _globalDSManager->activate(_device, this); _descriptorSet = _globalDSManager->getGlobalDescriptorSet(); _pipelineUBO->activate(_device, this); @@ -116,7 +116,6 @@ void RenderPipeline::destroy() { CC_SAFE_DELETE(_defaultTexture); - SamplerLib::destroyAll(); PipelineStateManager::destroyAll(); InstancedBuffer::destroyInstancedBuffer(); } diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index 2afa90acbc..4706fc48d4 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -26,12 +26,13 @@ #pragma once #include "Define.h" +#include "GlobalDescriptorSetManager.h" #include "PipelineSceneData.h" #include "PipelineUBO.h" #include "base/CoreStd.h" -#include "GlobalDescriptorSetManager.h" #include "helper/DefineMap.h" #include "scene/Camera.h" +#include "scene/Model.h" namespace cc { namespace gfx { @@ -56,7 +57,7 @@ public: RenderPipeline(); ~RenderPipeline() override; - virtual bool activate(); + virtual bool activate(gfx::Swapchain *swapchain); virtual void destroy(); virtual bool initialize(const RenderPipelineInfo &info); virtual void render(const vector &cameras); @@ -80,6 +81,9 @@ public: inline gfx::Device * getDevice() { return _device; } RenderStage * getRenderstageByName(const String &name) const; + inline scene::Model *getProfiler() const { return _profiler; } + inline void setProfiler(scene::Model *value) { _profiler = value; } + protected: static RenderPipeline *instance; @@ -92,11 +96,12 @@ protected: uint _tag = 0; String _constantMacros; - gfx::Device * _device = nullptr; - GlobalDSManager * _globalDSManager = nullptr; - gfx::DescriptorSet * _descriptorSet = nullptr; - PipelineUBO * _pipelineUBO = nullptr; - PipelineSceneData * _pipelineSceneData = nullptr; + gfx::Device * _device = nullptr; + GlobalDSManager * _globalDSManager = nullptr; + gfx::DescriptorSet *_descriptorSet = nullptr; + PipelineUBO * _pipelineUBO = nullptr; + PipelineSceneData * _pipelineSceneData = nullptr; + scene::Model * _profiler = nullptr; // has not initBuiltinRes, // create temporary default Texture to binding sampler2d gfx::Texture *_defaultTexture = nullptr; diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index a345e9e406..c7e9c20fd9 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -41,7 +41,7 @@ namespace cc { namespace pipeline { -bool castBoundsInitialized = false; +bool castBoundsInitialized = false; scene::AABB castWorldBounds; RenderObject genRenderObject(const scene::Model *model, const scene::Camera *camera) { @@ -176,17 +176,18 @@ void sceneCulling(RenderPipeline *pipeline, scene::Camera *camera) { isShadowMap = true; } - RenderObjectList renderObjects; + RenderObjectList renderObjects; if (skyBox->enabled && skyBox->model && (camera->clearFlag & skyboxFlag)) { renderObjects.emplace_back(genRenderObject(skyBox->model, camera)); } + const auto visibility = camera->visibility; + for (auto *model : scene->getModels()) { // filter model by view visibility if (model->getEnabled()) { - const auto visibility = camera->visibility; - const auto *const node = model->getNode(); + const auto *const node = model->getNode(); if ((model->getNode() && ((visibility & node->getLayer()) == node->getLayer())) || (visibility & model->getVisFlags())) { // shadow render Object diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp index e005334f20..317eea401b 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp @@ -29,13 +29,11 @@ #include "MainFlow.h" #include "gfx-base/GFXBuffer.h" #include "gfx-base/GFXCommandBuffer.h" +#include "gfx-base/GFXDef.h" #include "gfx-base/GFXDescriptorSet.h" #include "gfx-base/GFXDevice.h" -#include "gfx-base/GFXFramebuffer.h" -#include "gfx-base/GFXQueue.h" -#include "gfx-base/GFXRenderPass.h" -#include "gfx-base/GFXSampler.h" -#include "gfx-base/GFXTexture.h" +#include "gfx-base/GFXSwapchain.h" +#include "gfx-base/states/GFXTextureBarrier.h" #include "platform/Application.h" namespace cc { @@ -50,8 +48,6 @@ namespace { (dst)[(offset) + 1] = (src).y; \ (dst)[(offset) + 2] = (src).z; \ (dst)[(offset) + 3] = (src).w; - -const uint GBUFFER_POS_INDEX = 1; } // namespace void srgbToLinear(gfx::Color *out, const gfx::Color &gamma) { @@ -64,17 +60,14 @@ framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferTexture[GBUFFER_COU framegraph::FrameGraph::stringToHandle("gbufferAlbedoTexture"), framegraph::FrameGraph::stringToHandle("gbufferPositionTexture"), framegraph::FrameGraph::stringToHandle("gbufferNormalTexture"), - framegraph::FrameGraph::stringToHandle("gbufferEmissiveTexture") -}; -framegraph::StringHandle DeferredPipeline::fgStrHandleDepthTexture = framegraph::FrameGraph::stringToHandle("depthTexture"); -framegraph::StringHandle DeferredPipeline::fgStrHandleDepthTexturePost = framegraph::FrameGraph::stringToHandle("depthTexturePost"); + framegraph::FrameGraph::stringToHandle("gbufferEmissiveTexture")}; +framegraph::StringHandle DeferredPipeline::fgStrHandleDepthTexture = framegraph::FrameGraph::stringToHandle("depthTexture"); framegraph::StringHandle DeferredPipeline::fgStrHandleLightingOutTexture = framegraph::FrameGraph::stringToHandle("lightingOutputTexture"); -framegraph::StringHandle DeferredPipeline::fgStrHandleBackBufferTexture = framegraph::FrameGraph::stringToHandle("backBufferTexture"); -framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferPass = framegraph::FrameGraph::stringToHandle("deferredGbufferPass"); -framegraph::StringHandle DeferredPipeline::fgStrHandleLightingPass = framegraph::FrameGraph::stringToHandle("deferredLightingPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferPass = framegraph::FrameGraph::stringToHandle("deferredGbufferPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleLightingPass = framegraph::FrameGraph::stringToHandle("deferredLightingPass"); framegraph::StringHandle DeferredPipeline::fgStrHandleTransparentPass = framegraph::FrameGraph::stringToHandle("deferredTransparentPass"); -framegraph::StringHandle DeferredPipeline::fgStrHandleSsprPass = framegraph::FrameGraph::stringToHandle("deferredSSPRPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleSsprPass = framegraph::FrameGraph::stringToHandle("deferredSSPRPass"); framegraph::StringHandle DeferredPipeline::fgStrHandlePostprocessPass = framegraph::FrameGraph::stringToHandle("deferredPostPass"); bool DeferredPipeline::initialize(const RenderPipelineInfo &info) { @@ -93,15 +86,15 @@ bool DeferredPipeline::initialize(const RenderPipelineInfo &info) { return true; } -bool DeferredPipeline::activate() { +bool DeferredPipeline::activate(gfx::Swapchain *swapchain) { _macros.setValue("CC_PIPELINE_TYPE", static_cast(1.0)); - if (!RenderPipeline::activate()) { + if (!RenderPipeline::activate(swapchain)) { CC_LOG_ERROR("RenderPipeline active failed."); return false; } - if (!activeRenderer()) { + if (!activeRenderer(swapchain)) { CC_LOG_ERROR("DeferredPipeline startup failed!"); return false; } @@ -109,104 +102,13 @@ bool DeferredPipeline::activate() { return true; } -void DeferredPipeline::initFrameGraphExternalTexture() { - // gbuffer descriptorset setup - gfx::SamplerInfo sinfo{ - gfx::Filter::LINEAR, - gfx::Filter::LINEAR, - gfx::Filter::NONE, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - }; - const auto samplerHash = SamplerLib::genSamplerHash(sinfo); - auto *const sampler = SamplerLib::getSampler(samplerHash); - - // create external gbuffer and depth - gfx::TextureInfo info = { - gfx::TextureType::TEX2D, - gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, - gfx::Format::RGBA8, - _width, - _height, - }; - - gfx::TextureInfo infoPos = { - gfx::TextureType::TEX2D, - gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, - gfx::Format::RGBA16F, // POSITON cannot use RGBA8 - _width, - _height, - }; - - for (uint i = 0; i < GBUFFER_COUNT; ++i) { - if (i != GBUFFER_POS_INDEX) { - fgTextureGbuffer[i] = new framegraph::Resource(info); - fgTextureGbuffer[i]->createPersistent(); - } else { - fgTextureGbuffer[i] = new framegraph::Resource(infoPos); - fgTextureGbuffer[i]->createPersistent(); - } - - // bind global descriptor - auto *tex = static_cast(fgTextureGbuffer[i]->getDeviceObject()); - _descriptorSet->bindSampler(static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_ALBEDOMAP) + i, sampler); - _descriptorSet->bindTexture(static_cast(PipelineGlobalBindings::SAMPLER_GBUFFER_ALBEDOMAP) + i, tex); - } - _descriptorSet->update(); - - gfx::TextureInfo depthInfo = { - gfx::TextureType::TEX2D, - gfx::TextureUsageBit::DEPTH_STENCIL_ATTACHMENT, - _device->getDepthStencilFormat(), - _width, - _height, - }; - - fgTextureDepth = new framegraph::Resource(depthInfo); - fgTextureDepth->createPersistent(); -} - -void DeferredPipeline::destroyFrameGraphExternalTexture() { - // gbuffer descriptorset setup - for (auto *node : fgTextureGbuffer) { - // bind global descriptor - if (node) { - auto *tex = static_cast(node->getDeviceObject()); - CC_SAFE_DELETE(tex); - CC_SAFE_DELETE(node); - } - } - - if (fgTextureDepth) { - auto *depthTex = static_cast(fgTextureDepth->getDeviceObject()); - CC_SAFE_DELETE(depthTex); - CC_SAFE_DELETE(fgTextureDepth); - } -} - -void DeferredPipeline::prepareFrameGraph() { - // prepare for the backbuffer, if the gfx::Texture is nullptr, cocos will use swapchain texture when create framebuffer - _fg.getBlackboard().put(fgStrHandleBackBufferTexture, _fg.importExternal(fgStrHandleBackBufferTexture, fgTextureBackBuffer)); - _fg.getBlackboard().put(fgStrHandleDepthTexturePost, _fg.importExternal(fgStrHandleDepthTexturePost, fgTextureDepthPost)); - - for (uint i = 0; i < 4; ++i) { - _fg.getBlackboard().put(fgStrHandleGbufferTexture[i], _fg.importExternal(fgStrHandleGbufferTexture[i], *fgTextureGbuffer[i])); - } - - _fg.getBlackboard().put(fgStrHandleDepthTexture, _fg.importExternal(fgStrHandleDepthTexture, *fgTextureDepth)); -} - void DeferredPipeline::render(const vector &cameras) { - static gfx::TextureBarrier *present{_device->createTextureBarrier({{gfx::AccessType::COLOR_ATTACHMENT_WRITE}, {gfx::AccessType::PRESENT}})}; - static gfx::Texture * backBuffer{nullptr}; _commandBuffers[0]->begin(); - _pipelineUBO->updateGlobalUBO(); + _pipelineUBO->updateGlobalUBO(cameras[0]); _pipelineUBO->updateMultiCameraUBO(cameras); for (auto *camera : cameras) { _fg.reset(); - prepareFrameGraph(); sceneCulling(this, camera); _frameGraphCamera = camera; for (auto *const flow : _flows) { @@ -214,12 +116,19 @@ void DeferredPipeline::render(const vector &cameras) { } _fg.compile(); - //_fg.exportGraphViz("fg_vis.dot"); + + /* * + static bool exported = false; + if (!exported) { + _fg.exportGraphViz("fg_vis.dot"); + exported = true; + } + // */ + _fg.execute(); _pipelineUBO->incCameraUBOOffset(); } - _commandBuffers[0]->pipelineBarrier(nullptr, &present, &backBuffer, 1); _commandBuffers[0]->end(); _device->flushCommands(_commandBuffers); _device->getQueue()->submit(_commandBuffers); @@ -238,7 +147,7 @@ gfx::InputAssembler *DeferredPipeline::getIAByRenderArea(const gfx::Rect &rect) return _quadIA[value]; } - gfx::Buffer *vb = nullptr; + gfx::Buffer * vb = nullptr; gfx::InputAssembler *ia = nullptr; createQuadInputAssembler(_quadIB, &vb, &ia); _quadVB.push_back(vb); @@ -250,12 +159,10 @@ gfx::InputAssembler *DeferredPipeline::getIAByRenderArea(const gfx::Rect &rect) } void DeferredPipeline::genQuadVertexData(gfx::SurfaceTransform /*surfaceTransform*/, const gfx::Rect &renderArea, float *vbData) { - auto width = float(_width); - auto height = float(_height); - auto minX = float(renderArea.x) / width; - auto maxX = float(renderArea.x + renderArea.width) / width; - auto minY = float(renderArea.y) / height; - auto maxY = float(renderArea.y + renderArea.height) / height; + float minX = static_cast(renderArea.x) / static_cast(_width); + float maxX = static_cast(renderArea.x + renderArea.width) / static_cast(_width); + float minY = static_cast(renderArea.y) / static_cast(_height); + float maxY = static_cast(renderArea.y + renderArea.height) / static_cast(_height); if (_device->getCapabilities().screenSpaceSignY > 0) { std::swap(minY, maxY); } @@ -285,7 +192,7 @@ bool DeferredPipeline::createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer if (*quadVB == nullptr) { *quadVB = _device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, vbSize, vbStride}); + gfx::MemoryUsageBit::DEVICE, vbSize, vbStride}); } if (*quadVB == nullptr) { @@ -304,14 +211,16 @@ bool DeferredPipeline::createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer gfx::Rect DeferredPipeline::getRenderArea(scene::Camera *camera, bool onScreen) { gfx::Rect renderArea; - uint w; - uint h; + + float w; + float h; if (onScreen) { - w = camera->window->hasOnScreenAttachments && static_cast(_device->getSurfaceTransform()) % 2 ? camera->height : camera->width; - h = camera->window->hasOnScreenAttachments && static_cast(_device->getSurfaceTransform()) % 2 ? camera->width : camera->height; + gfx::Swapchain *swapchain = camera->window->swapchain; + w = static_cast(swapchain && toNumber(swapchain->getSurfaceTransform()) % 2 ? camera->height : camera->width); + h = static_cast(swapchain && toNumber(swapchain->getSurfaceTransform()) % 2 ? camera->width : camera->height); } else { - w = camera->width; - h = camera->height; + w = static_cast(camera->width); + h = static_cast(camera->height); } const auto &viewport = camera->viewPort; @@ -336,32 +245,26 @@ void DeferredPipeline::destroyQuadInputAssembler() { _quadIA.clear(); } -bool DeferredPipeline::activeRenderer() { +bool DeferredPipeline::activeRenderer(gfx::Swapchain *swapchain) { _commandBuffers.push_back(_device->getCommandBuffer()); auto *const sharedData = _pipelineSceneData->getSharedData(); - gfx::SamplerInfo info{ + gfx::Sampler *const sampler = _device->getSampler({ gfx::Filter::POINT, gfx::Filter::POINT, gfx::Filter::NONE, gfx::Address::CLAMP, gfx::Address::CLAMP, gfx::Address::CLAMP, - {}, - {}, - {}, - {}, - }; - const uint samplerHash = SamplerLib::genSamplerHash(info); - gfx::Sampler *const sampler = SamplerLib::getSampler(samplerHash); + }); // Main light sampler binding - this->_descriptorSet->bindSampler(SHADOWMAP::BINDING, sampler); - this->_descriptorSet->bindTexture(SHADOWMAP::BINDING, getDefaultTexture()); + _descriptorSet->bindSampler(SHADOWMAP::BINDING, sampler); + _descriptorSet->bindTexture(SHADOWMAP::BINDING, getDefaultTexture()); // Spot light sampler binding - this->_descriptorSet->bindSampler(SPOTLIGHTINGMAP::BINDING, sampler); - this->_descriptorSet->bindTexture(SPOTLIGHTINGMAP::BINDING, getDefaultTexture()); + _descriptorSet->bindSampler(SPOTLIGHTINGMAP::BINDING, sampler); + _descriptorSet->bindTexture(SPOTLIGHTINGMAP::BINDING, getDefaultTexture()); _descriptorSet->update(); @@ -374,7 +277,7 @@ bool DeferredPipeline::activeRenderer() { uint ibSize = ibStride * 6; if (_quadIB == nullptr) { _quadIB = _device->createBuffer({gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, - gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, ibSize, ibStride}); + gfx::MemoryUsageBit::DEVICE, ibSize, ibStride}); } if (_quadIB == nullptr) { @@ -384,9 +287,8 @@ bool DeferredPipeline::activeRenderer() { unsigned int ibData[] = {0, 1, 2, 1, 3, 2}; _quadIB->update(ibData, sizeof(ibData)); - _width = _device->getWidth(); - _height = _device->getHeight(); - initFrameGraphExternalTexture(); + _width = swapchain->getWidth(); + _height = swapchain->getHeight(); return true; } @@ -397,31 +299,10 @@ void DeferredPipeline::resize(uint width, uint height) { } _width = width; _height = height; - destroyDeferredData(); - - destroyFrameGraphExternalTexture(); - initFrameGraphExternalTexture(); } void DeferredPipeline::destroy() { destroyQuadInputAssembler(); - destroyDeferredData(); - - for (auto *node : fgTextureGbuffer) { - CC_SAFE_DELETE(node); - } - - CC_SAFE_DELETE(fgTextureDepth); - - if (_descriptorSet) { - _descriptorSet->getBuffer(UBOGlobal::BINDING)->destroy(); - _descriptorSet->getBuffer(UBOCamera::BINDING)->destroy(); - _descriptorSet->getBuffer(UBOShadow::BINDING)->destroy(); - _descriptorSet->getSampler(SHADOWMAP::BINDING)->destroy(); - _descriptorSet->getTexture(SHADOWMAP::BINDING)->destroy(); - _descriptorSet->getSampler(SPOTLIGHTINGMAP::BINDING)->destroy(); - _descriptorSet->getTexture(SPOTLIGHTINGMAP::BINDING)->destroy(); - } for (auto &it : _renderPasses) { CC_DESTROY(it.second); @@ -433,13 +314,10 @@ void DeferredPipeline::destroy() { RenderPipeline::destroy(); } -void DeferredPipeline::destroyDeferredData() { -} - gfx::Color DeferredPipeline::getClearcolor(scene::Camera *camera) { - auto *const sceneData = getPipelineSceneData(); - auto *const sharedData = sceneData->getSharedData(); - gfx::Color clearColor{0.0, 0.0, 0.0, 1.0F}; + auto *const sceneData = getPipelineSceneData(); + auto *const sharedData = sceneData->getSharedData(); + gfx::Color clearColor{0.0, 0.0, 0.0, 1.0F}; if (camera->clearFlag & static_cast(gfx::ClearFlagBit::COLOR)) { if (sharedData->isHDR) { srgbToLinear(&clearColor, camera->clearColor); diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h index ff8e113f68..279f21d72f 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h @@ -27,12 +27,12 @@ #include +#include +#include "frame-graph/FrameGraph.h" +#include "frame-graph/Handle.h" #include "gfx-base/GFXBuffer.h" #include "gfx-base/GFXInputAssembler.h" #include "pipeline/RenderPipeline.h" -#include "frame-graph/FrameGraph.h" -#include "frame-graph/Handle.h" -#include namespace cc { namespace pipeline { @@ -49,10 +49,10 @@ struct CC_DLL DeferredRenderData { }; enum class DeferredInsertPoint { - IP_GBUFFER = 100, - IP_LIGHTING = 200, + IP_GBUFFER = 100, + IP_LIGHTING = 200, IP_TRANSPARENT = 220, - IP_SSPR = 300, + IP_SSPR = 300, IP_POSTPROCESS = 400, IP_INVALID }; @@ -64,7 +64,7 @@ public: bool initialize(const RenderPipelineInfo &info) override; void destroy() override; - bool activate() override; + bool activate(gfx::Swapchain *swapchain) override; void render(const vector &cameras) override; void resize(uint width, uint height) override; @@ -78,21 +78,16 @@ public: void genQuadVertexData(gfx::SurfaceTransform surfaceTransform, const gfx::Rect &renderArea, float *data); framegraph::FrameGraph &getFrameGraph() { return _fg; } - gfx::Color getClearcolor(scene::Camera *camera); - void prepareFrameGraph(); - void initFrameGraphExternalTexture(); - void destroyFrameGraphExternalTexture(); - uint getWidth() const { return _width; } - uint getHeight() const { return _height; } - scene::Camera *getFrameGraphCamera() const { return _frameGraphCamera; } - gfx::InputAssembler *getIAByRenderArea(const gfx::Rect &rect); + gfx::Color getClearcolor(scene::Camera *camera); + uint getWidth() const { return _width; } + uint getHeight() const { return _height; } + scene::Camera * getFrameGraphCamera() const { return _frameGraphCamera; } + gfx::InputAssembler * getIAByRenderArea(const gfx::Rect &rect); private: - bool activeRenderer(); + bool activeRenderer(gfx::Swapchain *swapchain); bool createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer **quadVB, gfx::InputAssembler **quadIA); void destroyQuadInputAssembler(); - void destroyDeferredData(); - void generateDeferredRenderData(); gfx::Buffer * _lightsUBO = nullptr; LightList _validLights; @@ -106,38 +101,26 @@ private: std::vector _quadVB; std::unordered_map _quadIA; - uint _width = 0; - uint _height = 0; + uint _width = 0; + uint _height = 0; framegraph::FrameGraph _fg; - scene::Camera *_frameGraphCamera = nullptr; + scene::Camera * _frameGraphCamera = nullptr; public: - // deferred resource name declear - static framegraph::StringHandle fgStrHandleGbufferTexture[4]; // deal as external resource - static framegraph::StringHandle fgStrHandleDepthTexture; // deal as external resource - static framegraph::StringHandle fgStrHandleDepthTexturePost; // deal as external resource - static framegraph::StringHandle fgStrHandleLightingOutTexture; - static framegraph::StringHandle fgStrHandleBackBufferTexture; // buffer get from swapchain, used for queuepresent + static constexpr uint GBUFFER_COUNT = 4; - // deferred pass name declear + // deferred resource names + static framegraph::StringHandle fgStrHandleGbufferTexture[GBUFFER_COUNT]; + static framegraph::StringHandle fgStrHandleDepthTexture; + static framegraph::StringHandle fgStrHandleLightingOutTexture; + + // deferred pass names static framegraph::StringHandle fgStrHandleGbufferPass; static framegraph::StringHandle fgStrHandleLightingPass; static framegraph::StringHandle fgStrHandleTransparentPass; static framegraph::StringHandle fgStrHandleSsprPass; static framegraph::StringHandle fgStrHandlePostprocessPass; - - // external resources of framegraph - static const uint GBUFFER_COUNT = 4; - - // In deferred pipeline, all passes use the same global descriptorset. - // In vulkan spec, a descriptorset cannot update after first use, so we should bind all bindings before any pass executing - // So gbuffer should create gfx texture and binding to global descriptorset in DeferredPipeline::activeRenderer - // gbuffer's depth is not the same as post-process - framegraph::Texture *fgTextureGbuffer[GBUFFER_COUNT] = {nullptr}; - framegraph::Texture *fgTextureDepth = nullptr; - framegraph::Texture fgTextureDepthPost; - framegraph::Texture fgTextureBackBuffer; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp index 1abce76e09..09ae69066d 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp @@ -32,13 +32,13 @@ #include "../RenderQueue.h" #include "DeferredPipeline.h" #include "MainFlow.h" +#include "frame-graph/DevicePass.h" +#include "frame-graph/DevicePassResourceTable.h" +#include "frame-graph/Resource.h" #include "gfx-base/GFXCommandBuffer.h" #include "gfx-base/GFXDevice.h" #include "gfx-base/GFXFramebuffer.h" #include "gfx-base/GFXQueue.h" -#include "frame-graph/DevicePassResourceTable.h" -#include "frame-graph/DevicePass.h" -#include "frame-graph/Resource.h" namespace cc { namespace pipeline { @@ -76,7 +76,7 @@ GbufferStage::~GbufferStage() = default; bool GbufferStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; - _phaseID = getPhaseID("deferred"); + _phaseID = getPhaseID("default"); return true; } @@ -143,11 +143,10 @@ void GbufferStage::dispenseRenderObject2Queues() { queue->sort(); } } -void GbufferStage::recordCommands(DeferredPipeline *pipeline, gfx::RenderPass *renderPass) -{ - auto *cmdBuff = pipeline->getCommandBuffers()[0]; +void GbufferStage::recordCommands(DeferredPipeline *pipeline, gfx::RenderPass *renderPass) { + auto *cmdBuff = pipeline->getCommandBuffers()[0]; - // descriptorset bindings + // DescriptorSet bindings uint const globalOffsets[] = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); @@ -164,56 +163,83 @@ void GbufferStage::render(scene::Camera *camera) { }; auto *pipeline = static_cast(_pipeline); - _renderArea = pipeline->getRenderArea(camera, false); + _renderArea = pipeline->getRenderArea(camera, false); - // render area is not oriented, copy buffer must be called outsize of renderpass, it shouldnot be called in execute lambda expression + // render area is not oriented, copy buffer must be called outsize of RenderPass, it should not be called in execute lambda expression // If there are only transparent object, lighting pass is ignored, we should call getIAByRenderArea here (void)pipeline->getIAByRenderArea(_renderArea); auto gbufferSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { // gbuffer setup - gfx::Color clearColor = {0.0, 0.0, 0.0, 0.0}; + gfx::TextureInfo gbufferInfo = { + gfx::TextureType::TEX2D, + gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, + gfx::Format::RGBA8, + pipeline->getWidth(), + pipeline->getHeight(), + }; + gfx::TextureInfo gbufferInfoFloat = { + gfx::TextureType::TEX2D, + gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, + gfx::Format::RGBA16F, + pipeline->getWidth(), + pipeline->getHeight(), + }; + for (int i = 0; i < DeferredPipeline::GBUFFER_COUNT; ++i) { + if (i % 3) { // positions & normals need more precision + data.gbuffer[i] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[i], gbufferInfoFloat); + } else { + data.gbuffer[i] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[i], gbufferInfo); + } + } + + gfx::Color clearColor{0.0, 0.0, 0.0, 0.0}; framegraph::RenderTargetAttachment::Descriptor colorInfo; - colorInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorInfo.loadOp = gfx::LoadOp::CLEAR; - colorInfo.clearColor = clearColor; - colorInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; - for (int i = 0; i < 4; ++i) { - data.gbuffer[i] = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i])), colorInfo); + colorInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorInfo.loadOp = gfx::LoadOp::CLEAR; + colorInfo.clearColor = clearColor; + colorInfo.beginAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + colorInfo.endAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + for (int i = 0; i < DeferredPipeline::GBUFFER_COUNT; ++i) { + data.gbuffer[i] = builder.write(data.gbuffer[i], colorInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i], data.gbuffer[i]); } // depth setup - framegraph::RenderTargetAttachment::Descriptor depthInfo; - depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthInfo.loadOp = gfx::LoadOp::CLEAR; - depthInfo.clearDepth = camera->clearDepth; - depthInfo.clearStencil = camera->clearStencil; - depthInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + gfx::TextureInfo depthTexInfo = { + gfx::TextureType::TEX2D, + gfx::TextureUsageBit::DEPTH_STENCIL_ATTACHMENT, + gfx::Format::DEPTH_STENCIL, + pipeline->getWidth(), + pipeline->getHeight(), + }; + data.depth = builder.create(DeferredPipeline::fgStrHandleDepthTexture, depthTexInfo); - data.depth = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)), depthInfo); + framegraph::RenderTargetAttachment::Descriptor depthInfo; + depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthInfo.loadOp = gfx::LoadOp::CLEAR; + depthInfo.clearDepth = camera->clearDepth; + depthInfo.clearStencil = camera->clearStencil; + depthInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + data.depth = builder.write(data.depth, depthInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); // viewport setup - gfx::Viewport viewport{ _renderArea.x, _renderArea.y, _renderArea.width, _renderArea.height, 0.F, 1.F}; + gfx::Viewport viewport{_renderArea.x, _renderArea.y, _renderArea.width, _renderArea.height, 0.F, 1.F}; builder.setViewport(viewport, _renderArea); }; - auto gbufferExec = [&] (RenderData const &data, const framegraph::DevicePassResourceTable &table) { - CC_UNUSED_PARAM(data); - auto *pipeline = static_cast(RenderPipeline::getInstance()); - assert(pipeline != nullptr); - auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); - assert(stage != nullptr); - gfx::RenderPass *renderPass = table.getRenderPass().get(); - assert(renderPass != nullptr); + auto gbufferExec = [&](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) { + auto * pipeline = static_cast(RenderPipeline::getInstance()); + auto * stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); + gfx::RenderPass *renderPass = table.getRenderPass(); stage->recordCommands(pipeline, renderPass); }; // Command 'updateBuffer' must be recorded outside render passes, cannot put them in execute lambda dispenseRenderObject2Queues(); - auto *cmdBuff = pipeline->getCommandBuffers()[0]; + auto *cmdBuff = pipeline->getCommandBuffers()[0]; _instancedQueue->uploadBuffers(cmdBuff); _batchedQueue->uploadBuffers(cmdBuff); diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp index c1ce430864..1ddb7c5d12 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp @@ -25,6 +25,7 @@ #include "LightingStage.h" #include "../BatchedBuffer.h" +#include "../Define.h" #include "../InstancedBuffer.h" #include "../PipelineStateManager.h" #include "../PlanarShadowQueue.h" @@ -33,6 +34,8 @@ #include "../RenderQueue.h" #include "DeferredPipeline.h" #include "base/Utils.h" +#include "frame-graph/Blackboard.h" +#include "frame-graph/Handle.h" #include "gfx-base/GFXCommandBuffer.h" #include "gfx-base/GFXDescriptorSet.h" #include "gfx-base/GFXDevice.h" @@ -42,9 +45,6 @@ #include "scene/RenderScene.h" #include "scene/Sphere.h" #include "scene/SphereLight.h" -#include "../Define.h" -#include "frame-graph/Blackboard.h" -#include "frame-graph/Handle.h" namespace cc { namespace pipeline { @@ -61,9 +61,9 @@ void linearToSrgb(gfx::Color *out, const gfx::Color &linear) { out->z = std::sqrt(linear.z); } -const String STAGE_NAME = "LightingStage"; -const uint MAX_REFLECTOR_SIZE = 5; -framegraph::StringHandle reflectTexHandle = framegraph::FrameGraph::stringToHandle("reflectionTex"); +const String STAGE_NAME = "LightingStage"; +const uint MAX_REFLECTOR_SIZE = 5; +framegraph::StringHandle reflectTexHandle = framegraph::FrameGraph::stringToHandle("reflectionTex"); framegraph::StringHandle denoiseTexHandle[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprClearPass[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprCompReflectPass[MAX_REFLECTOR_SIZE]; @@ -73,19 +73,19 @@ framegraph::StringHandle ssprRenderPass[MAX_REFLECTOR_SIZE]; void initStrHandle() { std::string tmp; for (int i = 0; i < MAX_REFLECTOR_SIZE; ++i) { - tmp = std::string("denoiseTexureHandle") + std::to_string(i); + tmp = std::string("denoiseTexureHandle") + std::to_string(i); denoiseTexHandle[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = std::string("ssprClearPss") + std::to_string(i); + tmp = std::string("ssprClearPss") + std::to_string(i); ssprClearPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = std::string("ssprReflectPass") + std::to_string(i); + tmp = std::string("ssprReflectPass") + std::to_string(i); ssprCompReflectPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = std::string("ssprDenoisePass") + std::to_string(i); + tmp = std::string("ssprDenoisePass") + std::to_string(i); ssprCompDenoisePass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = std::string("ssprRenderPass") + std::to_string(i); + tmp = std::string("ssprRenderPass") + std::to_string(i); ssprRenderPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); } } @@ -110,7 +110,6 @@ bool LightingStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; _phaseID = getPhaseID("default"); - _defPhaseID = getPhaseID("deferred"); _reflectionPhaseID = getPhaseID("reflection"); initStrHandle(); @@ -118,11 +117,7 @@ bool LightingStage::initialize(const RenderStageInfo &info) { } void LightingStage::gatherLights(scene::Camera *camera) { - auto *pipeline = dynamic_cast(_pipeline); - if (!pipeline) { - return; - } - + auto * pipeline = static_cast(_pipeline); auto *const sceneData = _pipeline->getPipelineSceneData(); auto *const sharedData = sceneData->getSharedData(); @@ -255,7 +250,7 @@ void LightingStage::initLightingBuffer() { auto *const device = _pipeline->getDevice(); // color/pos/dir/angle 都是vec4存储, 最后一个vec4只要x存储光源个数 - uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); + uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); uint totalSize = stride * _maxDeferredLights; // create lighting buffer and view @@ -267,13 +262,11 @@ void LightingStage::initLightingBuffer() { stride, }; _deferredLitsBufs = device->createBuffer(bfInfo); - assert(_deferredLitsBufs != nullptr); } if (_deferredLitsBufView == nullptr) { gfx::BufferViewInfo bvInfo = {_deferredLitsBufs, 0, totalSize}; _deferredLitsBufView = device->createBuffer(bvInfo); - assert(_deferredLitsBufView != nullptr); _descriptorSet->bindBuffer(static_cast(ModelLocalBindings::UBO_FORWARD_LIGHTS), _deferredLitsBufView); } @@ -292,7 +285,7 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); } - // create descriptorset/layout + // create descriptor set/layout gfx::DescriptorSetLayoutInfo layoutInfo = {localDescriptorSetLayout.bindings}; _descLayout = device->createDescriptorSetLayout(layoutInfo); @@ -310,14 +303,6 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { _reflectionComp->init(_device, 8, 8); _reflectionRenderQueue = CC_NEW(RenderQueue(std::move(info))); - - gfx::SamplerInfo samplerInfo; - samplerInfo.minFilter = gfx::Filter::LINEAR; - samplerInfo.magFilter = gfx::Filter::LINEAR; - samplerInfo.addressU = gfx::Address::CLAMP; - samplerInfo.addressV = gfx::Address::CLAMP; - samplerInfo.addressW = gfx::Address::CLAMP; - _ssprSample = pipeline->getDevice()->createSampler(samplerInfo); } void LightingStage::destroy() { @@ -328,50 +313,6 @@ void LightingStage::destroy() { RenderStage::destroy(); CC_SAFE_DELETE(_reflectionComp); - CC_SAFE_DELETE(_ssprSample); -} - -void LightingStage::recordCommandsLit(DeferredPipeline *pipeline, gfx::RenderPass *renderPass) { - auto *const sceneData = pipeline->getPipelineSceneData(); - - auto *cmdBuff = pipeline->getCommandBuffers()[0]; - vector dynamicOffsets = {0}; - cmdBuff->bindDescriptorSet(localSet, _descriptorSet, dynamicOffsets); - - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); - // get pso and draw quad - auto rendeArea = pipeline->getRenderArea(pipeline->getFrameGraphCamera(), false); - - scene::Pass *pass = sceneData->getSharedData()->deferredLightPass; - gfx::Shader *shader = sceneData->getSharedData()->deferredLightPassShader; - gfx::InputAssembler *inputAssembler = pipeline->getIAByRenderArea(rendeArea); - gfx::PipelineState *pState = PipelineStateManager::getOrCreatePipelineState( - pass, shader, inputAssembler, renderPass); - assert(pState != nullptr); - - cmdBuff->bindPipelineState(pState); - cmdBuff->bindInputAssembler(inputAssembler); - cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); - cmdBuff->draw(inputAssembler); -} - -void LightingStage::recordCommandsTransparent(DeferredPipeline *pipeline, gfx::RenderPass *renderPass) { - auto *cmdBuff = pipeline->getCommandBuffers()[0]; - - vector dynamicOffsets = {0}; - cmdBuff->bindDescriptorSet(static_cast(SetIndex::LOCAL), _descriptorSet, dynamicOffsets); - - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuff->bindDescriptorSet(static_cast(SetIndex::GLOBAL), pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); - - // transparent - for (auto *queue : _renderQueues) { - queue->sort(); - queue->recordCommandBuffer(_device, renderPass, cmdBuff); - } - - //_planarShadowQueue->recordCommandBuffer(_device, renderPass, cmdBuff); } void LightingStage::fgLightingPass(scene::Camera *camera) { @@ -380,15 +321,15 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { _descriptorSet->update(); struct RenderData { - framegraph::TextureHandle gbuffer[4]; // read from gbuffer stage - framegraph::TextureHandle lightOutput; // output texture + framegraph::TextureHandle gbuffer[4]; // read from gbuffer stage + framegraph::TextureHandle lightOutput; // output texture framegraph::TextureHandle depth; }; - auto * pipeline = static_cast(_pipeline); + auto * pipeline = static_cast(_pipeline); gfx::Color clearColor = pipeline->getClearcolor(camera); - auto lightingSetup = [&] (framegraph::PassNodeBuilder &builder, RenderData &data) { + auto lightingSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { // read gbuffer for (int i = 0; i < 4; i++) { data.gbuffer[i] = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i]))); @@ -397,48 +338,77 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { // read depth, as an attachment framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - depthAttachmentInfo.clearColor = gfx::Color(); - depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; + depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; - data.depth = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture))); + data.depth = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)); data.depth = builder.write(data.depth, depthAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); // write to lighting output - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = clearColor; - colorAttachmentInfo.endAccesses = {gfx::AccessType::COLOR_ATTACHMENT_READ}; - framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; colorTexInfo.width = pipeline->getWidth(); colorTexInfo.height = pipeline->getHeight(); + data.lightOutput = builder.create(DeferredPipeline::fgStrHandleLightingOutTexture, colorTexInfo); - data.lightOutput = builder.create(DeferredPipeline::fgStrHandleLightingOutTexture, colorTexInfo); - data.lightOutput = builder.write(data.lightOutput, colorAttachmentInfo); + framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = clearColor; + colorAttachmentInfo.beginAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + colorAttachmentInfo.endAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + data.lightOutput = builder.write(data.lightOutput, colorAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture, data.lightOutput); // set render area - auto renderArea = pipeline->getRenderArea(camera, false); - gfx::Viewport viewport{ renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; + auto renderArea = pipeline->getRenderArea(camera, false); + gfx::Viewport viewport{renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; builder.setViewport(viewport, renderArea); }; - auto lightingExec = [] (RenderData const &data, const framegraph::DevicePassResourceTable &table) { - CC_UNUSED_PARAM(data); - auto *pipeline = static_cast(RenderPipeline::getInstance()); - assert(pipeline != nullptr); - auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); - assert(stage != nullptr); - gfx::RenderPass *renderPass = table.getRenderPass().get(); - assert(renderPass != nullptr); + auto lightingExec = [](RenderData const &data, const framegraph::DevicePassResourceTable &table) { + auto * pipeline = static_cast(RenderPipeline::getInstance()); + auto * stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); + auto *const sceneData = pipeline->getPipelineSceneData(); - stage->recordCommandsLit(pipeline, renderPass); + auto * cmdBuff = pipeline->getCommandBuffers()[0]; + vector dynamicOffsets = {0}; + cmdBuff->bindDescriptorSet(localSet, stage->_descriptorSet, dynamicOffsets); + + uint const globalOffsets[] = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + // get PSO and draw quad + auto rendeArea = pipeline->getRenderArea(pipeline->getFrameGraphCamera(), false); + + scene::Pass * pass = sceneData->getSharedData()->deferredLightPass; + gfx::Shader * shader = sceneData->getSharedData()->deferredLightPassShader; + gfx::InputAssembler *inputAssembler = pipeline->getIAByRenderArea(rendeArea); + gfx::PipelineState * pState = PipelineStateManager::getOrCreatePipelineState( + pass, shader, inputAssembler, table.getRenderPass()); + + gfx::SamplerInfo sinfo{ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + }; + auto *sampler = pipeline->getDevice()->getSampler(sinfo); + for (uint i = 0; i < DeferredPipeline::GBUFFER_COUNT; ++i) { + pass->getDescriptorSet()->bindTexture(i, table.getRead(data.gbuffer[i])); + pass->getDescriptorSet()->bindSampler(i, sampler); + } + pass->getDescriptorSet()->update(); + + cmdBuff->bindPipelineState(pState); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); + cmdBuff->draw(inputAssembler); }; pipeline->getFrameGraph().addPass(static_cast(DeferredInsertPoint::IP_LIGHTING), DeferredPipeline::fgStrHandleLightingPass, lightingSetup, lightingExec); @@ -446,21 +416,22 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { void LightingStage::fgTransparent(scene::Camera *camera) { struct RenderData { - framegraph::TextureHandle lightOutput; // output texture + framegraph::TextureHandle lightOutput; // output texture framegraph::TextureHandle depth; }; - auto * pipeline = static_cast(_pipeline); + auto * pipeline = static_cast(_pipeline); gfx::Color clearColor = pipeline->getClearcolor(camera); - auto transparentSetup = [&] (framegraph::PassNodeBuilder &builder, RenderData &data) { + auto transparentSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { // write to lighting output framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - colorAttachmentInfo.endAccesses = {gfx::AccessType::COLOR_ATTACHMENT_READ}; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + colorAttachmentInfo.beginAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + colorAttachmentInfo.endAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; - data.lightOutput = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture)); + data.lightOutput = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture)); bool lightingPassValid = data.lightOutput.isValid(); if (!lightingPassValid) { framegraph::Texture::Descriptor colorTexInfo; @@ -469,8 +440,8 @@ void LightingStage::fgTransparent(scene::Camera *camera) { colorTexInfo.width = pipeline->getWidth(); colorTexInfo.height = pipeline->getHeight(); - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = clearColor; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = clearColor; data.lightOutput = builder.create(DeferredPipeline::fgStrHandleLightingOutTexture, colorTexInfo); } @@ -478,43 +449,46 @@ void LightingStage::fgTransparent(scene::Camera *camera) { data.lightOutput = builder.write(data.lightOutput, colorAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture, data.lightOutput); - // read depth, as an attachment framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; + depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; + depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; - if (!lightingPassValid) { - depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - depthAttachmentInfo.clearColor = gfx::Color(); - } - - data.depth = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture))); + data.depth = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)); data.depth = builder.write(data.depth, depthAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); // set render area - auto renderArea = pipeline->getRenderArea(camera, false); - gfx::Viewport viewport{ renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; + auto renderArea = pipeline->getRenderArea(camera, false); + gfx::Viewport viewport{renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; builder.setViewport(viewport, renderArea); }; - auto transparentExec = [] (RenderData const &data, const framegraph::DevicePassResourceTable &table) { - CC_UNUSED_PARAM(data); + auto transparentExec = [](RenderData const & /*data*/, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(RenderPipeline::getInstance()); - assert(pipeline != nullptr); - auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); - assert(stage != nullptr); - gfx::RenderPass *renderPass = table.getRenderPass().get(); - assert(renderPass != nullptr); + auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); + auto *cmdBuff = pipeline->getCommandBuffers()[0]; - stage->recordCommandsTransparent(pipeline, renderPass); + vector dynamicOffsets = {0}; + cmdBuff->bindDescriptorSet(localSet, stage->_descriptorSet, dynamicOffsets); + + uint const globalOffsets[] = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + + // transparent + for (auto *queue : stage->_renderQueues) { + queue->sort(); + queue->recordCommandBuffer(pipeline->getDevice(), table.getRenderPass(), cmdBuff); + } + + //_planarShadowQueue->recordCommandBuffer(_device, renderPass, cmdBuff); }; putTransparentObj2Queue(); bool empty = true; - for (auto * node : _renderQueues) { + for (auto *node : _renderQueues) { if (!node->empty()) { empty = false; break; @@ -523,7 +497,7 @@ void LightingStage::fgTransparent(scene::Camera *camera) { if (!empty) { pipeline->getFrameGraph().addPass(static_cast(DeferredInsertPoint::IP_TRANSPARENT), - DeferredPipeline::fgStrHandleTransparentPass, transparentSetup, transparentExec); + DeferredPipeline::fgStrHandleTransparentPass, transparentSetup, transparentExec); } } @@ -542,8 +516,8 @@ void LightingStage::putTransparentObj2Queue() { const auto *const model = ro.model; for (auto *subModel : model->getSubModels()) { for (auto *pass : subModel->getPasses()) { - // TODO(xwx): need fallback of unlit and gizmo material. - if (pass->getPhase() != _phaseID && pass->getPhase() != _defPhaseID) continue; + // TODO(xwx): need to fallback unlit and gizmo material. + if (pass->getPhase() != _phaseID) continue; for (k = 0; k < _renderQueues.size(); k++) { _renderQueues[k]->insertRenderPass(ro, m, p); } @@ -556,7 +530,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // The max reflector objects is 5. // for each reflector, there are 4 pass, clear pass/reflection pass/denoise pass/render pass // each reflector has its own denoise texture, and will be used in render pass - // All the reflectors use the same reflect texture which is temp resoruce for the reflectors, and the reflect texture should be cleared for each reflector + // All the reflectors use the same reflect texture which is temp resource for the reflectors, and the reflect texture should be cleared for each reflector // we first calculate denoise textures of all reflectors one by one, the first 3 pass will be executed // then we render all reflectors one by one, the last render pass will be executed @@ -566,18 +540,18 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto *pipeline = static_cast(RenderPipeline::getInstance()); _denoiseIndex = 0; - _matViewProj = camera->matViewProj; + _matViewProj = camera->matViewProj; _reflectionElems.clear(); - // step 1 prepare clear model's reflection texture pass. if imageclear command is supported, this pass can be replaced by it - uint minSize = 512; - _ssprTexWidth = pipeline->getWidth(); + // step 1 prepare clear model's reflection texture pass. should switch to image clear command after available + uint minSize = 512; + _ssprTexWidth = pipeline->getWidth(); _ssprTexHeight = pipeline->getHeight(); if (_ssprTexHeight < _ssprTexWidth) { - _ssprTexWidth = minSize * _ssprTexWidth / _ssprTexHeight; + _ssprTexWidth = minSize * _ssprTexWidth / _ssprTexHeight; _ssprTexHeight = minSize; } else { - _ssprTexWidth = minSize; + _ssprTexWidth = minSize; _ssprTexHeight = minSize * _ssprTexHeight / _ssprTexWidth; } @@ -585,38 +559,36 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { framegraph::TextureHandle reflection; }; - auto clearSetup = [&] (framegraph::PassNodeBuilder &builder, DataClear &data) { - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = { 0.F, 0.F, 0.F, 0.F }; - colorAttachmentInfo.endAccesses = {gfx::AccessType::COMPUTE_SHADER_WRITE}; - + auto clearSetup = [&](framegraph::PassNodeBuilder &builder, DataClear &data) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA8; colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC | gfx::TextureUsageBit::TRANSFER_DST; colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - colorTexInfo.flags = gfx::TextureFlagBit::IMMUTABLE; + data.reflection = builder.create(reflectTexHandle, colorTexInfo); - data.reflection = builder.create(reflectTexHandle, colorTexInfo); - data.reflection = builder.write(data.reflection, colorAttachmentInfo); + framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = {0.F, 0.F, 0.F, 0.F}; + colorAttachmentInfo.endAccesses = {gfx::AccessType::COMPUTE_SHADER_WRITE}; + data.reflection = builder.write(data.reflection, colorAttachmentInfo); builder.writeToBlackboard(reflectTexHandle, data.reflection); builder.sideEffect(); }; - auto clearExec = [&] (DataClear const &data, const framegraph::DevicePassResourceTable &table) {}; + auto clearExec = [&](DataClear const &data, const framegraph::DevicePassResourceTable &table) {}; // step 2 prepare compute the reflection pass, contain 1 dispatch commands, compute pipeline struct DataCompReflect { - framegraph::TextureHandle reflection; // compute result texture - framegraph::TextureHandle lightingOut; // read from lighting pass output texture - framegraph::TextureHandle gbufferPosition; // read from gbuffer.positon texture + framegraph::TextureHandle reflection; // compute result texture + framegraph::TextureHandle lightingOut; // read from lighting pass output texture + framegraph::TextureHandle gbufferPosition; // read from gbuffer.positon texture }; - auto compReflectSetup = [&] (framegraph::PassNodeBuilder &builder, DataCompReflect &data) { - // if there is no attachment in the pass, renderpass willn't be created - // read lightingout as input + auto compReflectSetup = [&](framegraph::PassNodeBuilder &builder, DataCompReflect &data) { + // if there is no attachment in the pass, render pass will not be created + // read lighting out as input data.lightingOut = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture))); builder.writeToBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture, data.lightingOut); @@ -632,8 +604,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC | gfx::TextureUsageBit::TRANSFER_DST; colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - colorTexInfo.flags = gfx::TextureFlagBit::IMMUTABLE; - data.reflection = builder.create(reflectTexHandle, colorTexInfo); + data.reflection = builder.create(reflectTexHandle, colorTexInfo); } data.reflection = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(reflectTexHandle))); @@ -643,7 +614,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { builder.writeToBlackboard(reflectTexHandle, data.reflection); }; - auto compReflectExec = [&] (DataCompReflect const &data, const framegraph::DevicePassResourceTable &table) { + auto compReflectExec = [&](DataCompReflect const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(RenderPipeline::getInstance()); assert(pipeline != nullptr); auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); @@ -656,7 +627,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto *texLightingOut = static_cast(table.getRead(data.lightingOut)); auto *texPositon = static_cast(table.getRead(data.gbufferPosition)); - // step 1 pipelinebarrier before exec + // step 1 pipeline barrier before exec auto *cmdBuff = pipeline->getCommandBuffers()[0]; cmdBuff->pipelineBarrier(reflectionComp->getBarrierPre()); @@ -667,8 +638,8 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // layout(set = 0, binding = 3, rgba8) writeonly uniform lowp image2D reflectionTex; // set 0 gfx::DescriptorSet *reflectDesc = reflectionComp->getDescriptorSet(); - gfx::Sampler *sampler = reflectionComp->getSampler(); - gfx::Buffer *constBuffer = reflectionComp->getConstantsBuffer(); + gfx::Sampler * sampler = reflectionComp->getSampler(); + gfx::Buffer * constBuffer = reflectionComp->getConstantsBuffer(); reflectDesc->bindBuffer(0, constBuffer); reflectDesc->bindSampler(1, sampler); @@ -681,18 +652,26 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // set 1, subModel->getDescriptorSet(0) cmdBuff->bindPipelineState(const_cast(reflectionComp->getPipelineState())); - cmdBuff->bindDescriptorSet(0, reflectDesc); + cmdBuff->bindDescriptorSet(globalSet, reflectDesc); cmdBuff->dispatch(reflectionComp->getDispatchInfo()); }; + gfx::SamplerInfo samplerInfo; + samplerInfo.minFilter = gfx::Filter::POINT; + samplerInfo.magFilter = gfx::Filter::POINT; + samplerInfo.addressU = gfx::Address::CLAMP; + samplerInfo.addressV = gfx::Address::CLAMP; + samplerInfo.addressW = gfx::Address::CLAMP; + auto *ssprSampler = _device->getSampler(samplerInfo); + // step 3 prepare compute the denoise pass, contain 1 dispatch commands, compute pipeline struct DataCompDenoise { - framegraph::TextureHandle denoise; // each reflector has its own denoise texture - framegraph::TextureHandle reflection; // the texture from last pass + framegraph::TextureHandle denoise; // each reflector has its own denoise texture + framegraph::TextureHandle reflection; // the texture from last pass }; - auto compDenoiseSetup = [&] (framegraph::PassNodeBuilder &builder, DataCompDenoise &data) { - // if there is no attachment in the pass, renderpass willn't be created + auto compDenoiseSetup = [&](framegraph::PassNodeBuilder &builder, DataCompDenoise &data) { + // if there is no attachment in the pass, render pass will not be created // read reflectTexHandle data.reflection = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(reflectTexHandle))); builder.writeToBlackboard(reflectTexHandle, data.reflection); @@ -703,20 +682,19 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC; colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - colorTexInfo.flags = gfx::TextureFlagBit::IMMUTABLE; - data.denoise = builder.create(denoiseTexHandle[_denoiseIndex], colorTexInfo); + data.denoise = builder.create(denoiseTexHandle[_denoiseIndex], colorTexInfo); data.denoise = builder.write(data.denoise); builder.writeToBlackboard(denoiseTexHandle[_denoiseIndex], data.denoise); }; - auto compDenoiseExec = [&] (DataCompDenoise const &data, const framegraph::DevicePassResourceTable &table) { + auto compDenoiseExec = [&](DataCompDenoise const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(RenderPipeline::getInstance()); assert(pipeline != nullptr); auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); assert(stage != nullptr); - auto *denoiseTex = static_cast(table.getWrite(data.denoise)); + auto *denoiseTex = static_cast(table.getWrite(data.denoise)); auto *reflectionTex = static_cast(table.getRead(data.reflection)); ReflectionComp *reflectionComp = stage->getReflectionComp(); @@ -725,22 +703,22 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto *cmdBuff = pipeline->getCommandBuffers()[0]; cmdBuff->pipelineBarrier(nullptr, const_cast(reflectionComp->getBarrierBeforeDenoise()), {reflectionTex, denoiseTex}); - // bind descriptorset + // bind descriptor set reflectionComp->getDenoiseDescriptorSet()->bindTexture(0, reflectionTex); reflectionComp->getDenoiseDescriptorSet()->bindSampler(0, reflectionComp->getSampler()); reflectionComp->getDenoiseDescriptorSet()->update(); stage->getRendElement().set->bindTexture(static_cast(ModelLocalBindings::STORAGE_REFLECTION), denoiseTex); - stage->getRendElement().set->bindSampler(static_cast(ModelLocalBindings::STORAGE_REFLECTION), stage->getSsprSampler()); + stage->getRendElement().set->bindSampler(static_cast(ModelLocalBindings::STORAGE_REFLECTION), ssprSampler); // for render stage usage stage->getRendElement().set->bindTexture(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), denoiseTex); - stage->getRendElement().set->bindSampler(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), stage->getSsprSampler()); + stage->getRendElement().set->bindSampler(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), ssprSampler); stage->getRendElement().set->update(); cmdBuff->bindPipelineState(const_cast(reflectionComp->getDenoisePipelineState())); - cmdBuff->bindDescriptorSet(0, const_cast(reflectionComp->getDenoiseDescriptorSet())); - cmdBuff->bindDescriptorSet(1, stage->getRendElement().set); + cmdBuff->bindDescriptorSet(globalSet, const_cast(reflectionComp->getDenoiseDescriptorSet())); + cmdBuff->bindDescriptorSet(materialSet, stage->getRendElement().set); cmdBuff->dispatch(reflectionComp->getDenioseDispatchInfo()); // pipeline barrier @@ -752,65 +730,65 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // step 4 prepare render reflector objects pass, graphics pipeline struct DataRender { - framegraph::TextureHandle denoise; // input texture - framegraph::TextureHandle lightingOut; // attachment, load and write - framegraph::TextureHandle depth; // attachment, load and write + framegraph::TextureHandle denoise; // input texture + framegraph::TextureHandle lightingOut; // attachment, load and write + framegraph::TextureHandle depth; // attachment, load and write }; - auto renderSetup = [&] (framegraph::PassNodeBuilder &builder, DataRender &data) { + auto renderSetup = [&](framegraph::PassNodeBuilder &builder, DataRender &data) { data.denoise = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(denoiseTexHandle[_denoiseIndex]))); builder.writeToBlackboard(denoiseTexHandle[_denoiseIndex], data.denoise); - // write lightingOut, as an attachment + // write lighting out, as an attachment framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - colorAttachmentInfo.clearColor = gfx::Color(); - colorAttachmentInfo.beginAccesses = {gfx::AccessType::COLOR_ATTACHMENT_READ}; - colorAttachmentInfo.endAccesses = {gfx::AccessType::COLOR_ATTACHMENT_READ}; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + colorAttachmentInfo.clearColor = gfx::Color(); + colorAttachmentInfo.beginAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; + colorAttachmentInfo.endAccesses = {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}; data.lightingOut = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture)), colorAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture, data.lightingOut); // read depth, as an attachment framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - depthAttachmentInfo.clearColor = gfx::Color(); + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; + depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + depthAttachmentInfo.clearColor = gfx::Color(); depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; - depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; + depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; data.depth = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)), depthAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); - auto renderArea = pipeline->getRenderArea(camera, false); - gfx::Viewport viewport{ renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; + auto renderArea = pipeline->getRenderArea(camera, false); + gfx::Viewport viewport{renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; builder.setViewport(viewport, renderArea); }; - auto renderExec = [&] (DataRender const &data, const framegraph::DevicePassResourceTable &table) { + auto renderExec = [&](DataRender const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(RenderPipeline::getInstance()); assert(pipeline != nullptr); auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); assert(stage != nullptr); - auto *cmdBuff = pipeline->getCommandBuffers()[0]; - RenderElem elem = stage->getRendElement(); + auto * cmdBuff = pipeline->getCommandBuffers()[0]; + RenderElem elem = stage->getRendElement(); // bind descriptor - cmdBuff->bindDescriptorSet(static_cast(SetIndex::GLOBAL), pipeline->getDescriptorSet()); + cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet()); - gfx::DescriptorSet *descLocal = elem.set; // submodel's descriptorset - auto *denoiseTex = static_cast(table.getRead(data.denoise)); + gfx::DescriptorSet *descLocal = elem.set; // sub model descriptor set + auto * denoiseTex = static_cast(table.getRead(data.denoise)); descLocal->bindTexture(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), denoiseTex); - descLocal->bindSampler(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), stage->getSsprSampler()); + descLocal->bindSampler(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), ssprSampler); descLocal->update(); - cmdBuff->bindDescriptorSet(static_cast(SetIndex::LOCAL), descLocal); + cmdBuff->bindDescriptorSet(localSet, descLocal); stage->getReflectRenderQueue()->clear(); stage->getReflectRenderQueue()->insertRenderPass(elem.renderObject, elem.modelIndex, elem.passIndex); - gfx::RenderPass *renderPass = table.getRenderPass().get(); + gfx::RenderPass *renderPass = table.getRenderPass(); stage->getReflectRenderQueue()->sort(); stage->getReflectRenderQueue()->recordCommandBuffer(pipeline->getDevice(), renderPass, cmdBuff); }; @@ -818,17 +796,17 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // step 5 add framegraph passes auto *const sceneData = _pipeline->getPipelineSceneData(); const auto &renderObjects = sceneData->getRenderObjects(); - uint m = 0; - uint p = 0; + uint m = 0; + uint p = 0; for (const auto &ro : renderObjects) { - const auto *model = ro.model; - const auto& subModels = model->getSubModels(); + const auto *model = ro.model; + const auto &subModels = model->getSubModels(); for (m = 0; m < subModels.size(); ++m) { - const auto &subModel = subModels[m]; - const auto& passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto &subModel = subModels[m]; + const auto &passes = subModel->getPasses(); + auto passCount = passes.size(); for (p = 0; p < passCount; ++p) { - auto* pass = passes[p]; + auto *pass = passes[p]; if (pass->getPhase() == _reflectionPhaseID) { RenderElem elem = {ro, subModel->getDescriptorSet(), m, p}; _reflectionElems.push_back(elem); @@ -854,16 +832,16 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { void LightingStage::render(scene::Camera *camera) { auto *pipeline = static_cast(RenderPipeline::getInstance()); - // if gbuffer pass is inexistent, depthHandle is invalid, and then lighting pass is needless. - // transparent objects drawed in lighting pass, canbe put in its own pass + // if gbuffer pass does not exist, skip lighting pass. + // transparent objects draw after lighting pass, can be automatically merged by FG if (pipeline->getFrameGraph().isPassExist(DeferredPipeline::fgStrHandleGbufferPass)) { fgLightingPass(camera); } fgTransparent(camera); - // if lighting pass is inexistence, ignore sspr pass now. - // when clear image api is available, better way can be applied. + // if lighting pass does not exist, skip SSPR pass. + // switch to clear image API when available if (pipeline->getFrameGraph().isPassExist(DeferredPipeline::fgStrHandleLightingPass)) { fgSsprPass(camera); } diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.h b/native/cocos/renderer/pipeline/deferred/LightingStage.h index 10f0b688ed..4f6d4a22b7 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.h +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.h @@ -41,10 +41,10 @@ struct DeferredRenderData; class DeferredPipeline; struct RenderElem { - RenderObject renderObject; + RenderObject renderObject; gfx::DescriptorSet *set; - uint modelIndex; - uint passIndex; + uint modelIndex; + uint passIndex; }; class CC_DLL LightingStage : public RenderStage { @@ -57,17 +57,15 @@ public: bool initialize(const RenderStageInfo &info) override; void activate(RenderPipeline *pipeline, RenderFlow *flow) override; void destroy() override; - void renderBAK(scene::Camera *camera); void render(scene::Camera *camera) override; - ReflectionComp *getReflectionComp() {return _reflectionComp;} - RenderElem getRendElement(); - void addDenoiseIndex() {_denoiseIndex = (_denoiseIndex + 1) % _reflectionElems.size();} - RenderQueue *getReflectRenderQueue() const {return _reflectionRenderQueue;} - uint getSsprTexWidth() const { return _ssprTexWidth; } - uint getSsprTexHeight() const { return _ssprTexHeight; } - Mat4 getMatViewProj() const { return _matViewProj; } - gfx::Sampler *getSsprSampler() const { return _ssprSample; } + ReflectionComp *getReflectionComp() { return _reflectionComp; } + RenderElem getRendElement(); + void addDenoiseIndex() { _denoiseIndex = (_denoiseIndex + 1) % _reflectionElems.size(); } + RenderQueue * getReflectRenderQueue() const { return _reflectionRenderQueue; } + uint getSsprTexWidth() const { return _ssprTexWidth; } + uint getSsprTexHeight() const { return _ssprTexHeight; } + Mat4 getMatViewProj() const { return _matViewProj; } private: void gatherLights(scene::Camera *camera); @@ -75,8 +73,6 @@ private: void fgLightingPass(scene::Camera *camera); void fgTransparent(scene::Camera *camera); void fgSsprPass(scene::Camera *camera); - void recordCommandsLit(DeferredPipeline *pipeline, gfx::RenderPass *renderPass); - void recordCommandsTransparent(DeferredPipeline *pipeline, gfx::RenderPass *renderPass); void putTransparentObj2Queue(); @@ -84,7 +80,6 @@ private: PlanarShadowQueue * _planarShadowQueue{nullptr}; gfx::Rect _renderArea; uint _phaseID{0}; - uint _defPhaseID{0}; gfx::Buffer * _deferredLitsBufs{nullptr}; gfx::Buffer * _deferredLitsBufView{nullptr}; @@ -96,19 +91,17 @@ private: gfx::DescriptorSetLayout *_descLayout{nullptr}; uint _maxDeferredLights{UBODeferredLight::LIGHTS_PER_PASS}; - ReflectionComp * _reflectionComp{nullptr}; - RenderQueue * _reflectionRenderQueue{nullptr}; - uint _reflectionPhaseID{0}; + ReflectionComp *_reflectionComp{nullptr}; + RenderQueue * _reflectionRenderQueue{nullptr}; + uint _reflectionPhaseID{0}; std::vector _reflectionElems; - uint _denoiseIndex = 0; // use to get corrrect texture string handle + uint _denoiseIndex = 0; // use to get corrrect texture string handle // SSPR texture size - uint _ssprTexWidth = 0; + uint _ssprTexWidth = 0; uint _ssprTexHeight = 0; Mat4 _matViewProj; - - gfx::Sampler *_ssprSample = nullptr; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/deferred/MainFlow.cpp b/native/cocos/renderer/pipeline/deferred/MainFlow.cpp index a16ae2745e..d8c65ee5dd 100644 --- a/native/cocos/renderer/pipeline/deferred/MainFlow.cpp +++ b/native/cocos/renderer/pipeline/deferred/MainFlow.cpp @@ -30,8 +30,6 @@ #include "PostprocessStage.h" #include "gfx-base/GFXDescriptorSet.h" #include "gfx-base/GFXDevice.h" -#include "gfx-base/GFXRenderPass.h" -#include "gfx-base/GFXSampler.h" #include "pipeline/SceneCulling.h" namespace cc { diff --git a/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp b/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp index 809fac9541..ce6f96b4b0 100644 --- a/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp @@ -29,14 +29,14 @@ #include "../RenderQueue.h" #include "../forward/UIPhase.h" #include "DeferredPipeline.h" +#include "frame-graph/DevicePass.h" +#include "frame-graph/PassNodeBuilder.h" +#include "frame-graph/Resource.h" #include "gfx-base/GFXCommandBuffer.h" #include "gfx-base/GFXDevice.h" #include "gfx-base/GFXFramebuffer.h" #include "pipeline/Define.h" #include "scene/SubModel.h" -#include "frame-graph/PassNodeBuilder.h" -#include "frame-graph/DevicePass.h" -#include "frame-graph/Resource.h" namespace cc { namespace pipeline { @@ -52,7 +52,6 @@ RenderStageInfo PostprocessStage::initInfo = { }; const RenderStageInfo &PostprocessStage::getInitializeInfo() { return PostprocessStage::initInfo; } - PostprocessStage::PostprocessStage() { _uiPhase = CC_NEW(UIPhase); } @@ -89,22 +88,17 @@ void PostprocessStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); } - - gfx::DescriptorSetLayout *globalSetlayout = _device->createDescriptorSetLayout({globalDescriptorSetLayout.bindings}); - _globalSet = _device->createDescriptorSet({ globalSetlayout }); } void PostprocessStage::destroy() { - CC_SAFE_DELETE(_globalSetlayout); - CC_SAFE_DELETE(_globalSet); CC_SAFE_DELETE(_uiPhase); } void PostprocessStage::render(scene::Camera *camera) { - _fgStrHandlePostOut = DeferredPipeline::fgStrHandleBackBufferTexture; + static framegraph::StringHandle fgStrHandlePostProcessOutTexture = framegraph::FrameGraph::stringToHandle("postProcessOutputTexture"); struct RenderData { - framegraph::TextureHandle lightingOut; // read from lighting output - framegraph::TextureHandle backBuffer; // write to back buffer + framegraph::TextureHandle lightingOut; // read from lighting output + framegraph::TextureHandle backBuffer; // write to back buffer framegraph::TextureHandle depth; framegraph::TextureHandle placerholder; }; @@ -116,27 +110,8 @@ void PostprocessStage::render(scene::Camera *camera) { } _clearColors[0].w = camera->clearColor.w; - // in post-process, the output is not always backbuffer, its frame buffer should be camera->window->frameBuffer - // in cocos when camera->window->frameBuffer->_colorTextures[0] == nullptr, it means that render to swapchain image, that's backbuffer - // when camera->window->frameBuffer->_colorTextures[0] != nullptr, it means that render to a staging texture - auto * pipeline = static_cast(_pipeline); - if (camera->window->frameBuffer->getColorTextures()[0] != nullptr) { - _fgStrHandlePostOut = framegraph::FrameGraph::stringToHandle("fgStrHandlePostoutTexture"); - gfx::TextureInfo textureInfo = { - gfx::TextureType::TEX2D, - gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, - gfx::Format::RGBA16F, - camera->window->frameBuffer->getColorTextures()[0]->getWidth(), - camera->window->frameBuffer->getColorTextures()[0]->getHeight(), - }; - - auto *output = new framegraph::Resource(textureInfo); - output->createPersistent(camera->window->frameBuffer->getColorTextures()[0]); - - pipeline->getFrameGraph().getBlackboard().put(_fgStrHandlePostOut, pipeline->getFrameGraph().importExternal(_fgStrHandlePostOut, *output)); - } - - auto postSetup = [&] (framegraph::PassNodeBuilder &builder, RenderData &data) { + auto *pipeline = static_cast(_pipeline); + auto postSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { data.lightingOut = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture)); if (!data.lightingOut.isValid()) { framegraph::Texture::Descriptor colorTexInfo; @@ -151,79 +126,64 @@ void PostprocessStage::render(scene::Camera *camera) { data.lightingOut = builder.read(data.lightingOut); builder.writeToBlackboard(DeferredPipeline::fgStrHandleLightingOutTexture, data.lightingOut); - // backbuffer is as an attachment - if (camera->window->frameBuffer->getColorTextures()[0] != nullptr) { - data.placerholder = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleBackBufferTexture))); - builder.writeToBlackboard(DeferredPipeline::fgStrHandleBackBufferTexture, data.placerholder); - } - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.clearColor = _clearColors[0]; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.clearColor = _clearColors[0]; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; auto clearFlags = static_cast(camera->clearFlag); if (!hasFlag(clearFlags, gfx::ClearFlagBit::COLOR)) { if (hasFlag(clearFlags, static_cast(skyboxFlag))) { colorAttachmentInfo.loadOp = gfx::LoadOp::DISCARD; } else { - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - colorAttachmentInfo.beginAccesses = {gfx::AccessType::PRESENT}; + colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; } } - colorAttachmentInfo.endAccesses = {gfx::AccessType::PRESENT}; - data.backBuffer = framegraph::TextureHandle(builder.readFromBlackboard(_fgStrHandlePostOut)); + colorAttachmentInfo.beginAccesses = {gfx::AccessType::TRANSFER_READ}; + colorAttachmentInfo.endAccesses = {gfx::AccessType::TRANSFER_READ}; + + gfx::TextureInfo textureInfo = { + gfx::TextureType::TEX2D, + gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::TRANSFER_SRC, + gfx::Format::RGBA8, + camera->window->getWidth(), + camera->window->getHeight(), + }; + data.backBuffer = builder.create(fgStrHandlePostProcessOutTexture, textureInfo); data.backBuffer = builder.write(data.backBuffer, colorAttachmentInfo); - builder.writeToBlackboard(_fgStrHandlePostOut, data.backBuffer); + builder.writeToBlackboard(fgStrHandlePostProcessOutTexture, data.backBuffer); // depth framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; - depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; + depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}; - depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; + depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; - data.depth = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexturePost)), depthAttachmentInfo); - builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); + data.depth = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)); + if (data.depth.isValid()) { + data.depth = builder.write(data.depth, depthAttachmentInfo); + builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); + } - auto renderArea = pipeline->getRenderArea(camera, !camera->window->hasOffScreenAttachments); + auto renderArea = pipeline->getRenderArea(camera, camera->window->swapchain); (void)pipeline->getIAByRenderArea(renderArea); - gfx::Viewport viewport{ renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; + gfx::Viewport viewport{renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; builder.setViewport(viewport, renderArea); }; - auto postExec = [&] (RenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto *pipeline = static_cast(RenderPipeline::getInstance()); - assert(pipeline != nullptr); - auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); - assert(stage != nullptr); - gfx::RenderPass *renderPass = table.getRenderPass().get(); - assert(renderPass != nullptr); + auto postExec = [&](RenderData const &data, const framegraph::DevicePassResourceTable &table) { + auto * pipeline = static_cast(RenderPipeline::getInstance()); + auto * stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); + gfx::RenderPass *renderPass = table.getRenderPass(); // bind descriptor auto *lightingOut = static_cast(table.getRead(data.lightingOut)); - gfx::SamplerInfo info{ - gfx::Filter::LINEAR, - gfx::Filter::LINEAR, - gfx::Filter::NONE, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - }; - - auto * cmdBf = pipeline->getCommandBuffers()[0]; - stage->getGlobalSet()->bindBuffer(0, pipeline->getDescriptorSet()->getBuffer(0)); - stage->getGlobalSet()->bindBuffer(1, pipeline->getDescriptorSet()->getBuffer(1)); - const auto samplerHash = SamplerLib::genSamplerHash(info); - auto *const sampler = SamplerLib::getSampler(samplerHash); - stage->getGlobalSet()->bindSampler(static_cast(PipelineGlobalBindings::SAMPLER_LIGHTING_RESULTMAP), sampler); - stage->getGlobalSet()->bindTexture(static_cast(PipelineGlobalBindings::SAMPLER_LIGHTING_RESULTMAP), lightingOut); - stage->getGlobalSet()->update(); - + auto * cmdBuff = pipeline->getCommandBuffers()[0]; uint const globalOffsets[] = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBf->bindDescriptorSet(static_cast(SetIndex::GLOBAL), stage->getGlobalSet(), static_cast(std::size(globalOffsets)), globalOffsets); + cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); if (!pipeline->getPipelineSceneData()->getRenderObjects().empty()) { // post process @@ -232,79 +192,36 @@ void PostprocessStage::render(scene::Camera *camera) { gfx::Shader *sd = sceneData->getSharedData()->deferredPostPassShader; // get pso and draw quad - auto *camera = pipeline->getFrameGraphCamera(); - auto rendeArea = pipeline->getRenderArea(camera, !camera->window->hasOffScreenAttachments); - gfx::InputAssembler *ia = pipeline->getIAByRenderArea(rendeArea); - gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, ia, renderPass); + auto * camera = pipeline->getFrameGraphCamera(); + auto rendeArea = pipeline->getRenderArea(camera, camera->window->swapchain); + gfx::InputAssembler *ia = pipeline->getIAByRenderArea(rendeArea); + gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, ia, renderPass); assert(pso != nullptr); - cmdBf->bindPipelineState(pso); - cmdBf->bindInputAssembler(ia); - cmdBf->draw(ia); + pv->getDescriptorSet()->bindTexture(0, table.getRead(data.lightingOut)); + pv->getDescriptorSet()->bindSampler(0, pipeline->getDevice()->getSampler({ + gfx::Filter::POINT, + gfx::Filter::POINT, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + })); + pv->getDescriptorSet()->update(); + + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet(materialSet, pv->getDescriptorSet()); + cmdBuff->bindInputAssembler(ia); + cmdBuff->draw(ia); } - stage->getUIPhase()->render(pipeline->getFrameGraphCamera(), renderPass); - }; - - auto uiPhaseSetup = [&] (framegraph::PassNodeBuilder &builder, RenderData &data) { - // backbuffer is as an attachment - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.clearColor = _clearColors[0]; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - - auto clearFlags = static_cast(camera->clearFlag); - if (!hasFlag(clearFlags, gfx::ClearFlagBit::COLOR)) { - if (hasFlag(clearFlags, static_cast(skyboxFlag))) { - colorAttachmentInfo.loadOp = gfx::LoadOp::DISCARD; - } else { - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - colorAttachmentInfo.beginAccesses = {gfx::AccessType::PRESENT}; - } - } - - colorAttachmentInfo.endAccesses = {gfx::AccessType::PRESENT}; - - data.backBuffer = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleBackBufferTexture)), colorAttachmentInfo); - builder.writeToBlackboard(DeferredPipeline::fgStrHandleBackBufferTexture, data.backBuffer); - - framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; - depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_READ}; - - data.depth = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleDepthTexture)), depthAttachmentInfo); - builder.writeToBlackboard(DeferredPipeline::fgStrHandleDepthTexture, data.depth); - - auto renderArea = pipeline->getRenderArea(camera, !camera->window->hasOffScreenAttachments); - gfx::Viewport viewport{ renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.F, 1.F}; - builder.setViewport(viewport, renderArea); - }; - - auto uiPhaseExec = [&] (RenderData const &data, const framegraph::DevicePassResourceTable &table) { - CC_UNUSED_PARAM(data); - auto *pipeline = static_cast(RenderPipeline::getInstance()); - assert(pipeline != nullptr); - auto *stage = static_cast(pipeline->getRenderstageByName(STAGE_NAME)); - assert(stage != nullptr); - gfx::RenderPass *renderPass = table.getRenderPass().get(); - assert(renderPass != nullptr); - - stage->getGlobalSet()->bindBuffer(0, pipeline->getDescriptorSet()->getBuffer(0)); - stage->getGlobalSet()->bindBuffer(1, pipeline->getDescriptorSet()->getBuffer(1)); - - stage->getGlobalSet()->update(); - - auto * cmdBf = pipeline->getCommandBuffers()[0]; - uint const globalOffsets[] = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBf->bindDescriptorSet(static_cast(SetIndex::GLOBAL), stage->getGlobalSet(), static_cast(std::size(globalOffsets)), globalOffsets); stage->getUIPhase()->render(pipeline->getFrameGraphCamera(), renderPass); }; // add pass pipeline->getFrameGraph().addPass(static_cast(DeferredInsertPoint::IP_POSTPROCESS), DeferredPipeline::fgStrHandlePostprocessPass, postSetup, postExec); - pipeline->getFrameGraph().presentFromBlackboard(DeferredPipeline::fgStrHandleBackBufferTexture); + pipeline->getFrameGraph().presentFromBlackboard(fgStrHandlePostProcessOutTexture, camera->window->frameBuffer->getColorTextures()[0]); } + } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/deferred/PostprocessStage.h b/native/cocos/renderer/pipeline/deferred/PostprocessStage.h index 0371eca672..e63654734b 100644 --- a/native/cocos/renderer/pipeline/deferred/PostprocessStage.h +++ b/native/cocos/renderer/pipeline/deferred/PostprocessStage.h @@ -44,7 +44,6 @@ public: void destroy() override; void render(scene::Camera *camera) override; - gfx::DescriptorSet *getGlobalSet() { return _globalSet; } UIPhase *getUIPhase() { return _uiPhase; } private: @@ -53,11 +52,6 @@ private: uint _phaseID = 0; static RenderStageInfo initInfo; - - gfx::DescriptorSetLayout *_globalSetlayout = nullptr; - gfx::DescriptorSet *_globalSet = nullptr; - - framegraph::StringHandle _fgStrHandlePostOut; }; } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp b/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp index 1fb29a98b4..027c85f11c 100644 --- a/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp +++ b/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp @@ -5,6 +5,9 @@ namespace cc { ReflectionComp::~ReflectionComp() { + CC_DELETE(_compDescriptorSet->getLayout()); + CC_DELETE(_compPipelineState->getPipelineLayout()); + CC_SAFE_DESTROY(_compShader); CC_SAFE_DESTROY(_compDescriptorSetLayout); CC_SAFE_DESTROY(_compPipelineState); @@ -19,17 +22,6 @@ ReflectionComp::~ReflectionComp() { CC_SAFE_DESTROY(_localDescriptorSetLayout); CC_SAFE_DESTROY(_compConstantsBuffer); - CC_SAFE_DESTROY(_sampler); - - delete _barrierPre; - - for (auto *barrier : _barrierBeforeDenoise) { - delete barrier; - } - - for (auto *barrier : _barrierAfterDenoise) { - delete barrier; - } } namespace { @@ -66,7 +58,7 @@ void ReflectionComp::init(gfx::Device *dev, uint groupSizeX, uint groupSizeY) { gfx::SamplerInfo samplerInfo; samplerInfo.minFilter = gfx::Filter::POINT; samplerInfo.magFilter = gfx::Filter::POINT; - _sampler = _device->createSampler(samplerInfo); + _sampler = _device->getSampler(samplerInfo); uint maxInvocations = _device->getCapabilities().maxComputeWorkGroupInvocations; CCASSERT(_groupSizeX * _groupSizeY <= maxInvocations, "maxInvocations is too small"); @@ -107,10 +99,10 @@ void ReflectionComp::init(gfx::Device *dev, uint groupSizeX, uint groupSizeY) { gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE, }}; - _barrierPre = _device->createGlobalBarrier(infoPre); - _barrierBeforeDenoise.push_back(_device->createTextureBarrier(infoBeforeDenoise)); - _barrierBeforeDenoise.push_back(_device->createTextureBarrier(infoBeforeDenoise2)); - _barrierAfterDenoise.push_back(_device->createTextureBarrier(infoAfterDenoise)); + _barrierPre = _device->getGlobalBarrier(infoPre); + _barrierBeforeDenoise.push_back(_device->getTextureBarrier(infoBeforeDenoise)); + _barrierBeforeDenoise.push_back(_device->getTextureBarrier(infoBeforeDenoise2)); + _barrierAfterDenoise.push_back(_device->getTextureBarrier(infoAfterDenoise)); initReflectionRes(); initDenoiseRes(); diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 161fb29791..755f89b494 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -27,14 +27,7 @@ #include "../SceneCulling.h" #include "../shadow/ShadowFlow.h" #include "ForwardFlow.h" -#include "gfx-base/GFXBuffer.h" -#include "gfx-base/GFXCommandBuffer.h" -#include "gfx-base/GFXDescriptorSet.h" #include "gfx-base/GFXDevice.h" -#include "gfx-base/GFXQueue.h" -#include "gfx-base/GFXRenderPass.h" -#include "gfx-base/GFXSampler.h" -#include "gfx-base/GFXTexture.h" #include "platform/Application.h" #include "scene/RenderScene.h" @@ -52,7 +45,7 @@ namespace { (dst)[(offset) + 3] = (src).w; } // namespace -gfx::RenderPass *ForwardPipeline::getOrCreateRenderPass(gfx::ClearFlags clearFlags) { +gfx::RenderPass *ForwardPipeline::getOrCreateRenderPass(gfx::ClearFlags clearFlags, gfx::Swapchain *swapchain) { if (_renderPasses.count(clearFlags)) { return _renderPasses[clearFlags]; } @@ -60,8 +53,8 @@ gfx::RenderPass *ForwardPipeline::getOrCreateRenderPass(gfx::ClearFlags clearFla auto * device = gfx::Device::getInstance(); gfx::ColorAttachment colorAttachment; gfx::DepthStencilAttachment depthStencilAttachment; - colorAttachment.format = device->getColorFormat(); - depthStencilAttachment.format = device->getDepthStencilFormat(); + colorAttachment.format = swapchain->getColorTexture()->getFormat(); + depthStencilAttachment.format = swapchain->getDepthStencilTexture()->getFormat(); depthStencilAttachment.stencilStoreOp = gfx::StoreOp::STORE; depthStencilAttachment.depthStoreOp = gfx::StoreOp::STORE; @@ -107,8 +100,8 @@ bool ForwardPipeline::initialize(const RenderPipelineInfo &info) { return true; } -bool ForwardPipeline::activate() { - if (!RenderPipeline::activate()) { +bool ForwardPipeline::activate(gfx::Swapchain *swapchain) { + if (!RenderPipeline::activate(swapchain)) { CC_LOG_ERROR("RenderPipeline active failed."); return false; } @@ -122,10 +115,8 @@ bool ForwardPipeline::activate() { } void ForwardPipeline::render(const vector &cameras) { - static gfx::TextureBarrier *present{_device->createTextureBarrier({{gfx::AccessType::COLOR_ATTACHMENT_WRITE}, {gfx::AccessType::PRESENT}})}; - static gfx::Texture * backBuffer{nullptr}; _commandBuffers[0]->begin(); - _pipelineUBO->updateGlobalUBO(); + _pipelineUBO->updateGlobalUBO(cameras[0]); _pipelineUBO->updateMultiCameraUBO(cameras); for (auto *camera : cameras) { sceneCulling(this, camera); @@ -134,7 +125,6 @@ void ForwardPipeline::render(const vector &cameras) { } _pipelineUBO->incCameraUBOOffset(); } - _commandBuffers[0]->pipelineBarrier(nullptr, &present, &backBuffer, 1); _commandBuffers[0]->end(); _device->flushCommands(_commandBuffers); _device->getQueue()->submit(_commandBuffers); @@ -144,28 +134,22 @@ bool ForwardPipeline::activeRenderer() { _commandBuffers.push_back(_device->getCommandBuffer()); auto *const sharedData = _pipelineSceneData->getSharedData(); - gfx::SamplerInfo info{ + gfx::Sampler *const shadowMapSampler = _device->getSampler({ gfx::Filter::POINT, gfx::Filter::POINT, gfx::Filter::NONE, gfx::Address::CLAMP, gfx::Address::CLAMP, gfx::Address::CLAMP, - {}, - {}, - {}, - {}, - }; - const uint shadowMapSamplerHash = SamplerLib::genSamplerHash(info); - gfx::Sampler *const shadowMapSampler = SamplerLib::getSampler(shadowMapSamplerHash); + }); // Main light sampler binding - this->_descriptorSet->bindSampler(SHADOWMAP::BINDING, shadowMapSampler); - this->_descriptorSet->bindTexture(SHADOWMAP::BINDING, getDefaultTexture()); + _descriptorSet->bindSampler(SHADOWMAP::BINDING, shadowMapSampler); + _descriptorSet->bindTexture(SHADOWMAP::BINDING, getDefaultTexture()); // Spot light sampler binding - this->_descriptorSet->bindSampler(SPOTLIGHTINGMAP::BINDING, shadowMapSampler); - this->_descriptorSet->bindTexture(SPOTLIGHTINGMAP::BINDING, getDefaultTexture()); + _descriptorSet->bindSampler(SPOTLIGHTINGMAP::BINDING, shadowMapSampler); + _descriptorSet->bindTexture(SPOTLIGHTINGMAP::BINDING, getDefaultTexture()); _descriptorSet->update(); // update global defines when all states initialized. @@ -176,16 +160,6 @@ bool ForwardPipeline::activeRenderer() { } void ForwardPipeline::destroy() { - if (_descriptorSet) { - _descriptorSet->getBuffer(UBOGlobal::BINDING)->destroy(); - _descriptorSet->getBuffer(UBOCamera::BINDING)->destroy(); - _descriptorSet->getBuffer(UBOShadow::BINDING)->destroy(); - _descriptorSet->getSampler(SHADOWMAP::BINDING)->destroy(); - _descriptorSet->getTexture(SHADOWMAP::BINDING)->destroy(); - _descriptorSet->getSampler(SPOTLIGHTINGMAP::BINDING)->destroy(); - _descriptorSet->getTexture(SPOTLIGHTINGMAP::BINDING)->destroy(); - } - for (auto &it : _renderPasses) { CC_SAFE_DESTROY(it.second); } diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.h b/native/cocos/renderer/pipeline/forward/ForwardPipeline.h index 6d6482bc72..53e70a1e4d 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.h +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.h @@ -41,10 +41,10 @@ public: bool initialize(const RenderPipelineInfo &info) override; void destroy() override; - bool activate() override; + bool activate(gfx::Swapchain *swapchain) override; void render(const vector &cameras) override; - gfx::RenderPass *getOrCreateRenderPass(gfx::ClearFlags clearFlags); + gfx::RenderPass *getOrCreateRenderPass(gfx::ClearFlags clearFlags, gfx::Swapchain *swapchain); inline gfx::Buffer * getLightsUBO() const { return _lightsUBO; } inline const LightList & getValidLights() const { return _validLights; } diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index b36a22ebc4..5f3af10dec 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -117,15 +117,15 @@ void ForwardStage::render(scene::Camera *camera) { uint passIdx = 0; size_t k = 0; for (auto ro : renderObjects) { - const auto *const model = ro.model; - const auto& subModels = model->getSubModels(); - auto subModelCount = subModels.size(); + const auto *const model = ro.model; + const auto & subModels = model->getSubModels(); + auto subModelCount = subModels.size(); for (subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { - const auto& subModel = subModels[subModelIdx]; - const auto& passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto &subModel = subModels[subModelIdx]; + const auto &passes = subModel->getPasses(); + auto passCount = passes.size(); for (passIdx = 0; passIdx < passCount; ++passIdx) { - const auto& pass = passes[passIdx]; + const auto &pass = passes[passIdx]; if (pass->getPhase() != _phaseID) continue; if (pass->getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = InstancedBuffer::get(pass); @@ -143,7 +143,7 @@ void ForwardStage::render(scene::Camera *camera) { } } } - + for (auto *queue : _renderQueues) { queue->sort(); } @@ -156,8 +156,9 @@ void ForwardStage::render(scene::Camera *camera) { _planarShadowQueue->gatherShadowPasses(camera, cmdBuff); // render area is not oriented - uint w = camera->window->hasOnScreenAttachments && static_cast(_device->getSurfaceTransform()) % 2 ? camera->height : camera->width; - uint h = camera->window->hasOnScreenAttachments && static_cast(_device->getSurfaceTransform()) % 2 ? camera->width : camera->height; + bool flipWH = camera->window->swapchain && static_cast(camera->window->swapchain->getSurfaceTransform()) % 2; + auto w = static_cast(flipWH ? camera->height : camera->width); + auto h = static_cast(flipWH ? camera->width : camera->height); _renderArea.x = static_cast(camera->viewPort.x * w); _renderArea.y = static_cast(camera->viewPort.y * h); _renderArea.width = static_cast(camera->viewPort.z * w * sharedData->shadingScale); @@ -182,7 +183,9 @@ void ForwardStage::render(scene::Camera *camera) { auto * framebuffer = camera->window->frameBuffer; const auto &colorTextures = framebuffer->getColorTextures(); - auto *renderPass = !colorTextures.empty() && colorTextures[0] ? framebuffer->getRenderPass() : pipeline->getOrCreateRenderPass(static_cast(camera->clearFlag)); + auto *renderPass = camera->window->swapchain + ? pipeline->getOrCreateRenderPass(static_cast(camera->clearFlag), camera->window->swapchain) + : framebuffer->getRenderPass(); cmdBuff->beginRenderPass(renderPass, framebuffer, _renderArea, _clearColors, camera->clearDepth, camera->clearStencil); diff --git a/native/cocos/renderer/pipeline/forward/UIPhase.cpp b/native/cocos/renderer/pipeline/forward/UIPhase.cpp index 822c3e696f..1424ab7872 100644 --- a/native/cocos/renderer/pipeline/forward/UIPhase.cpp +++ b/native/cocos/renderer/pipeline/forward/UIPhase.cpp @@ -27,6 +27,7 @@ #include "gfx-base/GFXCommandBuffer.h" #include "pipeline/PipelineStateManager.h" #include "scene/RenderScene.h" +#include "scene/SubModel.h" namespace cc { namespace pipeline { @@ -42,29 +43,35 @@ void UIPhase::render(scene::Camera *camera, gfx::RenderPass *renderPass) { const auto &batches = camera->scene->getDrawBatch2Ds(); // Notice: The batches[0] is batchCount for (auto *batch : batches) { - bool visible = false; - if (camera->visibility & batch->visFlags) { - visible = true; - } - - if (!visible) continue; - int i = 0; - for (const auto *pass : batch->passes) { + if (!(camera->visibility & batch->visFlags)) continue; + for (size_t i = 0; i < batch->shaders.size(); ++i) { + const auto *pass = batch->passes[i]; if (pass->getPhase() != _phaseID) continue; - auto *const shader = batch->shaders[i]; - if (shader == nullptr) break; - auto *const inputAssembler = batch->inputAssembler; - auto *const ds = batch->descriptorSet; - auto * pso = cc::pipeline::PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); + auto *shader = batch->shaders[i]; + auto *inputAssembler = batch->inputAssembler; + auto *ds = batch->descriptorSet; + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindDescriptorSet(localSet, ds); cmdBuff->bindInputAssembler(inputAssembler); cmdBuff->draw(inputAssembler); - - ++i; } } + + auto *profiler = _pipeline->getProfiler(); + if (profiler && profiler->getEnabled() && camera->window->swapchain) { + auto *submodel = profiler->getSubModels()[0]; + auto *pass = submodel->getPasses()[0]; + auto *inputAssembler = submodel->getInputAssembler(); + auto *pso = PipelineStateManager::getOrCreatePipelineState( + pass, submodel->getShaders()[0], inputAssembler, renderPass); + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); + cmdBuff->bindDescriptorSet(localSet, submodel->getDescriptorSet()); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->draw(inputAssembler); + } } } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 39a326020e..c2cf3577fc 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -150,7 +150,7 @@ void ShadowFlow::resizeShadowMap(scene::Shadow **shadowInfo) { depth = device->createTexture({ gfx::TextureType::TEX2D, gfx::TextureUsageBit::DEPTH_STENCIL_ATTACHMENT, - device->getDepthStencilFormat(), + gfx::Format::DEPTH, width, height, }); @@ -175,25 +175,25 @@ 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) ? gfx::Format::R32F : gfx::Format::RGBA8; - + const gfx::ColorAttachment colorAttachment = { format, - gfx::SampleCount::X1, + gfx::SampleCount::ONE, gfx::LoadOp::CLEAR, gfx::StoreOp::STORE, - {}, - {}, + {gfx::AccessType::COLOR_ATTACHMENT_WRITE}, + {gfx::AccessType::FRAGMENT_SHADER_READ_TEXTURE}, }; const gfx::DepthStencilAttachment depthStencilAttachment = { - device->getDepthStencilFormat(), - gfx::SampleCount::X1, + gfx::Format::DEPTH, + gfx::SampleCount::ONE, gfx::LoadOp::CLEAR, gfx::StoreOp::DISCARD, gfx::LoadOp::CLEAR, gfx::StoreOp::DISCARD, - {}, - {}, + {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}, + {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE}, }; gfx::RenderPassInfo rpInfo; @@ -224,7 +224,7 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li gfx::Texture *depth = device->createTexture({ gfx::TextureType::TEX2D, gfx::TextureUsageBit::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsageBit::SAMPLED, - device->getDepthStencilFormat(), + gfx::Format::DEPTH, width, height, }); diff --git a/native/cocos/scene/RenderWindow.h b/native/cocos/scene/RenderWindow.h index 0a2470362a..1616dbbde1 100644 --- a/native/cocos/scene/RenderWindow.h +++ b/native/cocos/scene/RenderWindow.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -26,14 +26,17 @@ #pragma once #include "renderer/gfx-base/GFXFramebuffer.h" +#include "renderer/gfx-base/GFXTexture.h" namespace cc { namespace scene { struct RenderWindow final { - bool hasOnScreenAttachments{false}; - bool hasOffScreenAttachments{false}; + gfx::Swapchain * swapchain{nullptr}; gfx::Framebuffer *frameBuffer{nullptr}; + + inline uint getWidth() const { return frameBuffer->getColorTextures()[0]->getWidth(); } + inline uint getHeight() const { return frameBuffer->getColorTextures()[0]->getHeight(); } }; } // namespace scene diff --git a/native/cocos/scene/SubModel.h b/native/cocos/scene/SubModel.h index 2b95d927f5..7c1fdc9254 100644 --- a/native/cocos/scene/SubModel.h +++ b/native/cocos/scene/SubModel.h @@ -64,13 +64,14 @@ public: _subMesh->flatBuffers = flatBuffers; } - inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptSet; } - inline gfx::InputAssembler * getInputAssembler() const { return _ia; } - inline const std::vector &getPasses() const { return _passes; } - inline gfx::Shader * getPlanarInstanceShader() const { return _planarInstanceShader; } - inline gfx::Shader * getPlanarShader() const { return _planarShader; } - inline RenderPriority getPriority() const { return _priority; } - inline RenderingSubMesh * getSubMesh() const { return _subMesh; } + inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptSet; } + inline gfx::InputAssembler * getInputAssembler() const { return _ia; } + inline std::vector &getShaders() { return _shaders; } + inline const std::vector & getPasses() const { return _passes; } + inline gfx::Shader * getPlanarInstanceShader() const { return _planarInstanceShader; } + inline gfx::Shader * getPlanarShader() const { return _planarShader; } + inline RenderPriority getPriority() const { return _priority; } + inline RenderingSubMesh * getSubMesh() const { return _subMesh; } private: RenderPriority _priority{RenderPriority::DEFAULT}; diff --git a/native/docs/LINTER_AUTOFIX_GUIDE.md b/native/docs/LINTER_AUTOFIX_GUIDE.md index 3e3b5ae3be..5f6324668d 100644 --- a/native/docs/LINTER_AUTOFIX_GUIDE.md +++ b/native/docs/LINTER_AUTOFIX_GUIDE.md @@ -55,13 +55,13 @@ There are two important notes here: * The issues reported here all come from `clangd` the language server, which only supports a subset of `clang-tidy` rules. * It appears to be no 'fix-all' option in the editor. -This is where the `Command Runner` extension comes in and saves the day: we can assign a suitable key binding to run any CLI commands, e.g. invoke `clang-tidy` itself and fix all the issues in the current file! +This is where the `Command Runner` extension comes in and saves the day: we can assign a suitable key binding to run any CLI commands, e.g. invoke the `clang-tidy` proper and fix all the issues in the current file! * Open the VSCode settings (JSON) and add the following property: ![](imgs/vscode-settings.png) - ```json + ```js "command-runner.commands": { "tidy": "clang-tidy -fix '${file}'" } @@ -71,7 +71,7 @@ This is where the `Command Runner` extension comes in and saves the day: we can ![](imgs/keyboard-shortcut.png) - ```json + ```js { "key": "shift+alt+c", // set this to any key binding that works best for you "command": "command-runner.run", diff --git a/native/tools/bindings-generator/generator.py b/native/tools/bindings-generator/generator.py index 52abc71720..0d6a5e8795 100755 --- a/native/tools/bindings-generator/generator.py +++ b/native/tools/bindings-generator/generator.py @@ -639,7 +639,7 @@ class NativeType(object): else: return "ok &= sevalue_to_native(%s, &%s, %s)" % (convert_opts["in_value"], convert_opts["out_value"], context) - def to_string(self, generator): + def to_string(self, generator, omit_const=False): conversions = generator.config['conversions'] if 'native_types' in conversions: native_types_dict = conversions['native_types'] @@ -661,7 +661,7 @@ class NativeType(object): if use_typedef and self.canonical_type: name = self.canonical_type.namespaced_class_name - return "const " + name if (self.is_pointer and self.is_const) else name + return "const " + name if (self.is_pointer and self.is_const and not omit_const) else name def get_whole_name(self, generator): conversions = generator.config['conversions'] diff --git a/native/tools/bindings-generator/targets/spidermonkey/templates/ifunction_overloaded.c b/native/tools/bindings-generator/targets/spidermonkey/templates/ifunction_overloaded.c index fff73142e1..cb3d1dd354 100644 --- a/native/tools/bindings-generator/targets/spidermonkey/templates/ifunction_overloaded.c +++ b/native/tools/bindings-generator/targets/spidermonkey/templates/ifunction_overloaded.c @@ -21,7 +21,7 @@ static bool ${signature_name}(se::State& s) // NOLINT(readability-identifier-nam #set $count = 0 #while $count < $arg_idx #set $arg = $func.arguments[$count] - #set $arg_type = $arg.to_string($generator) + #set $arg_type = $arg.to_string($generator, omit_const=True) #if $arg.is_reference #set $holder_prefix="HolderType<"+$arg_type+", true>" #else diff --git a/native/tools/gfx-define-generator/generate.js b/native/tools/gfx-define-generator/generate.js index 8b8d8695ab..e747e7301b 100644 --- a/native/tools/gfx-define-generator/generate.js +++ b/native/tools/gfx-define-generator/generate.js @@ -27,11 +27,11 @@ for (let i = 2; i < argc; i++) { const defaultEngineRoot = ps.join(__dirname, '../../../engine'); const cacheFile = ps.join(__dirname, 'engine_root_cache.txt'); if (options.engineRoot) { - if (options.engineRoot === 'default') options.engineRoot = defaultEngineRoot; - if (fs.existsSync(options.engineRoot)) fs.writeFileSync(cacheFile, options.engineRoot); + if (options.engineRoot === 'default') { options.engineRoot = defaultEngineRoot; } + if (fs.existsSync(options.engineRoot)) { fs.writeFileSync(cacheFile, options.engineRoot); } } else { - if (fs.existsSync(cacheFile)) options.engineRoot = fs.readFileSync(cacheFile); - if (!options.engineRoot) options.engineRoot = defaultEngineRoot; + if (fs.existsSync(cacheFile)) { options.engineRoot = fs.readFileSync(cacheFile); } + if (!options.engineRoot) { options.engineRoot = defaultEngineRoot; } } // TODO: remove this after state info refactor @@ -55,8 +55,8 @@ while (enumCap) { while (valueCap) { if (valueCap[2]) { val = Number.parseInt(valueCap[2]); - if (Number.isNaN(val)) val = valueCap[2]; - else val = `0x${val.toString(16)}`; + if (Number.isNaN(val)) { val = valueCap[2]; } + else { val = `0x${val.toString(16)}`; } e.customKey = true; } else { val++; @@ -77,7 +77,7 @@ header = header.replace(/\/\*.*?\*\//gs, ''); header = header.replace(/\s*[*&](.)/g, (_, c) => (c === '>' ? '' : ' ') + c); header = header.replace(/(?:\w*::)?vector<(.+?)>/g, '$1[]'); -const typedefRE = /using\s+(.+?)\s*=\s*(.+?);/gs; +const typedefRE = /^\s*using\s+(.+?)\s*=\s*(.+?);/gsm; const typedefMap = { lists: {}, others: [] }; let typedefCap = typedefRE.exec(header); while (typedefCap) { @@ -93,13 +93,13 @@ while (typedefCap) { const getMemberList = (() => { const getMatchingPair = (string, startIdx, begSymbol, endSymbol) => { - if (string[startIdx] !== begSymbol) return startIdx; + if (string[startIdx] !== begSymbol) { return startIdx; } let depth = 1; let i = startIdx + 1; for (; i < string.length; i++) { - if (string[i] === begSymbol) depth++; - if (string[i] === endSymbol) depth--; - if (depth === 0) break; + if (string[i] === begSymbol) { depth++; } + if (string[i] === endSymbol) { depth--; } + if (depth === 0) { break; } } return i; }; @@ -108,7 +108,7 @@ const getMemberList = (() => { let endIdx = string.length; let scopeReady = false; for (let i = startIdx; i < endIdx; ++i) { - if (string[i] === '/' && string[i+1] === '/') { // skip comments + if (string[i] === '/' && string[i + 1] === '/') { // skip comments i = string.indexOf('\n', i); } else if (!scopeReady && string[i] === '{') { begIdx = i + 1; @@ -123,19 +123,31 @@ const getMemberList = (() => { })(); const structRE = /struct\s+(\w+).*?{\s*(.+?)\s*};/gs; -const structMemberRE = /^\s*(const\w*\s*)?([\w\[\]]+)\s+?(\w+)(?:\s*=?\s*(.*?))?;(?:\s*\/\/\s*@ts-(.*?)$)?/gm; +const structMemberRE = /^\s*(const\w*\s*)?([\w[\]]+)\s+?(\w+)(?:\s*[={]?\s*(.*?)\s*}*\s*)?;(?:\s*\/\/\s*@ts-(.*?)$)?/gm; const structMap = {}; const replaceConstants = (() => { const strMap = { - MAX_ATTACHMENTS: 4, - INVALID_BINDING: -1, - SUBPASS_EXTERNAL: -1, nullptr: 'null!', '::': '.', }; + const constexprRE = /constexpr\s+\w+\s+(\w+)\s*=\s*(.*);/g; + let constexprCap = constexprRE.exec(header); + while (constexprCap) { + let val = constexprCap[2]; + if (val.endsWith('U')) { val = val.slice(0, -1); } + val = val.replace('~0', '-1'); + strMap[constexprCap[1]] = val; + constexprCap = constexprRE.exec(header); + } const constantsRE = new RegExp(Object.keys(strMap).reduce((acc, cur) => `${acc}|${cur}`, '').slice(1), 'g'); return (str) => str.replace(constantsRE, (match) => strMap[match]); })(); +const getArrayValue = (decayedType, value) => { + const count = Number.parseInt(value); + if (Number.isNaN(count)) { return `[${value}]`; } + const ctorStr = `new ${decayedType}(), `; + return `[${ctorStr.repeat(count).slice(0, -2)}]`; +}; let structCap = structRE.exec(header); while (structCap) { const struct = structMap[structCap[1]] = {}; @@ -151,35 +163,31 @@ while (structCap) { if (typedefMap.lists[type]) { type = typedefMap.lists[type]; } else { - type = type.replace(/(\b)(?:uintptr_t|uint|int|float)(\b)/, '$1number$1'); + type = type.replace(/(\b)(void)(\b)/, '$1number$1'); + type = type.replace(/(\b)(?:uint\w+?_t|int\w+?_t|float)(\b)/, '$1number$1'); type = type.replace(/(\b)(?:bool)(\b)/, '$1boolean$2'); type = type.replace(/(\b)(?:String)(\b)/, '$1string$2'); } - if (memberCap[1]) readonly = true; + if (memberCap[1]) { readonly = true; } const isArray = type.endsWith('[]'); const decayedType = isArray ? type.slice(0, -2) : type; let value = memberCap[4]; let n = Number.parseInt(value); if (!Number.isNaN(n)) { - if (!value.startsWith('0x')) value = n; // keep hexadecimal numbers + if (!value.startsWith('0x')) { value = n; } // keep hexadecimal numbers } else if (value) { value = replaceConstants(value); - value = value.replace(/{(.*?)}/, (_, value) => { - const count = Number.parseInt(value); - if (Number.isNaN(count)) return `[${value}]`; - const ctorStr = `new ${type.slice(0, -2)}(), `; - return `[${ctorStr.repeat(count).slice(0, -2)}]`; - }); + if (isArray) { value = getArrayValue(decayedType, value); } } else { - if (isArray) value = '[]'; - else if (type === 'string') value = '\'\''; - else value = `new ${type}()`; + if (isArray) { value = '[]'; } + else if (type === 'string') { value = '\'\''; } + else { value = `new ${type}()`; } } const info = struct.member[memberCap[3]] = { // all the overridable values - readonly, type, value, isArray, decayedType + readonly, type, value, isArray, decayedType, }; const directives = memberCap[5]; @@ -195,13 +203,13 @@ while (structCap) { } } + if (info.type === 'number' && info.value === 'null!') { info.value = 0; } memberCap = structMemberRE.exec(memberList); } structCap = structRE.exec(header); } - let output = ''; for (const name of Object.keys(enumMap)) { @@ -229,7 +237,7 @@ for (const typedef of typedefMap.others) { output += `\n`; for (const name of Object.keys(structMap)) { - if (name in ignoreList) continue; + if (name in ignoreList) { continue; } output += `export class ${name} {\n declare private _token: never; `; output += `// to make sure all usages must be an instance of this exact class, not assembled from plain object`; @@ -249,12 +257,12 @@ for (const name of Object.keys(structMap)) { output += ` ) {}\n`; if (!Object.keys(struct.member).some((k) => struct.member[k].readonly)) { - output += `\n public copy (info: ${name}) {\n`; + output += `\n public copy (info: Readonly<${name}>) {\n`; for (const key in struct.member) { const { decayedType, isArray } = struct.member[key]; if (isArray) { if (structMap[decayedType]) { // nested object - output += ` deepCopy(this.${key}, info.${key}, ${decayedType});\n` + output += ` deepCopy(this.${key}, info.${key}, ${decayedType});\n`; } else { output += ` this.${key} = info.${key}.slice();\n`; } @@ -271,7 +279,7 @@ for (const name of Object.keys(structMap)) { output += `}\n\n`; } -if (options.clear) output = ''; +if (options.clear) { output = ''; } const outputFile = options.debug ? `${__dirname}/define.ts` : ps.join(options.engineRoot, 'cocos/core/gfx/base/define.ts'); let source = fs.readFileSync(outputFile).toString(); @@ -282,7 +290,7 @@ const begIdx = begGuardCap ? begGuardCap.index + begGuardCap[0].length : undefin const endGuardRE = /\/\*\*\s*\*\s*=+\s*![A-Z ]+!/g; let endGuardCap = endGuardRE.exec(source); -if (endGuardCap) endGuardCap = endGuardRE.exec(source); +if (endGuardCap) { endGuardCap = endGuardRE.exec(source); } const endIdx = endGuardCap ? endGuardCap.index : undefined; fs.writeFileSync(outputFile, `${source.slice(0, begIdx)}\n\n${output}${source.slice(endIdx)}`); diff --git a/native/tools/license-upgrader/generate.js b/native/tools/license-upgrader/generate.js index a29c39cea3..15f2fe449b 100644 --- a/native/tools/license-upgrader/generate.js +++ b/native/tools/license-upgrader/generate.js @@ -51,7 +51,7 @@ const genHeader = (history) => { ****************************************************************************/\n\n`; return output; -} +}; const headerRE = /\/\*{5,}.*?\*{5,}\/\s*/s; @@ -60,7 +60,7 @@ const curYear = new Date().getFullYear(); const companyName = 'Xiamen Yaji Software Co., Ltd.'; const update = (path) => { const cmpPath = path.replace(/\\/g, '/'); - if (ignoreList.some((p) => cmpPath.includes(p))) return; + if (ignoreList.some((p) => cmpPath.includes(p))) { return; } let content = fs.readFileSync(path, { encoding: 'utf8' }); const history = []; @@ -105,4 +105,4 @@ const update = (path) => { }; const files = fsJetpack.find(`${__dirname}/../../cocos`, { matching: ['**/*.h', '**/*.cpp', '**/*.mm'] }); -for (const path of files) update(path); +for (const path of files) { update(path); } diff --git a/native/tools/tojs/gfx.ini b/native/tools/tojs/gfx.ini index 9a8872e7c7..f96c940598 100644 --- a/native/tools/tojs/gfx.ini +++ b/native/tools/tojs/gfx.ini @@ -36,14 +36,14 @@ replace_headers = classes = DeviceManager, # classes - GFXObject Context DescriptorSet DescriptorSetLayout Device Buffer CommandBuffer Framebuffer GlobalBarrier InputAssembler, - PipelineLayout PipelineState Queue RenderPass Sampler Shader Texture TextureBarrier, + GFXObject DescriptorSet DescriptorSetLayout Device Buffer CommandBuffer Framebuffer GlobalBarrier InputAssembler, + PipelineLayout PipelineState Queue RenderPass Sampler Shader Swapchain Texture TextureBarrier, # structs - Attribute BindingMappingInfo BlendState BlendTarget BufferInfo BufferTextureCopy BufferViewInfo ContextInfo Color ColorAttachment CommandBufferInfo, + Attribute BindingMappingInfo BlendState BlendTarget BufferInfo BufferTextureCopy BufferViewInfo Color ColorAttachment CommandBufferInfo, DepthStencilAttachment DepthStencilState DescriptorSetInfo DescriptorSetLayoutBinding DescriptorSetLayoutInfo DeviceCaps DeviceInfo, DispatchInfo DrawInfo Extent FramebufferInfo GlobalBarrierInfo IndirectBuffer InputAssemblerInfo InputState, MemoryStatus Offset PipelineLayoutInfo PipelineStateInfo QueueInfo RasterizerState Rect RenderPassInfo SamplerInfo ShaderInfo ShaderStage Size SubpassInfo SubpassDependency, - TextureBarrierInfo TextureBlit TextureCopy TextureInfo TextureSubresLayers TextureSubresRange TextureViewInfo Uniform, + SwapchainInfo TextureBarrierInfo TextureBlit TextureCopy TextureInfo TextureSubresLayers TextureSubresRange TextureViewInfo Uniform, UniformBlock UniformInputAttachment UniformSampler UniformSamplerTexture UniformStorageBuffer UniformStorageImage UniformTexture Viewport ; FormatInfo @@ -56,42 +56,41 @@ classes_need_extend = # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = Buffer::[Buffer getDevice initialize update], - CommandBuffer::[CommandBuffer getDevice execute updateBuffer copyBuffersToTexture bindDescriptorSet$ beginRenderPass$], - Framebuffer::[Framebuffer getDevice], - InputAssembler::[InputAssembler getDevice extractDrawInfo], - DescriptorSet::[DescriptorSet getDevice], - DescriptorSetLayout::[DescriptorSetLayout getDevice getBindingIndices descriptorIndices getDescriptorIndices], - PipelineLayout::[PipelineLayout getDevice], - PipelineState::[PipelineState getDevice], - Queue::[Queue getDevice submit$], - RenderPass::[RenderPass getDevice getColorAttachments getBindings getBindingIndices], - Sampler::[Sampler getDevice], - Shader::[Shader getDevice], - Texture::[Texture getDevice initialize], - Device::[Device copyBuffersToTexture copyTextureToBuffers createBuffer createTexture getInstance flushCommands$], - Context::[Context] +skip = Buffer::[Buffer initialize update], + CommandBuffer::[CommandBuffer execute updateBuffer copyBuffersToTexture], + Framebuffer::[Framebuffer], + InputAssembler::[InputAssembler], + DescriptorSet::[DescriptorSet], + DescriptorSetLayout::[DescriptorSetLayout getBindingIndices descriptorIndices getDescriptorIndices], + PipelineLayout::[PipelineLayout], + PipelineState::[PipelineState], + Queue::[Queue], + RenderPass::[RenderPass getColorAttachments getBindings getBindingIndices], + Shader::[Shader], + Swapchain::[Swapchain], + Texture::[Texture initialize], + Sampler::[Sampler], + GlobalBarrier::[GlobalBarrier], + TextureBarrier::[TextureBarrier], + Device::[Device copyBuffersToTexture copyTextureToBuffers createBuffer createTexture getInstance] -getter_setter = Device::[gfxAPI surfaceTransform deviceName width height memoryStatus queue commandBuffer renderer vendor numDrawCalls numInstances numTris colorFormat depthStencilFormat capabilities], +getter_setter = Device::[gfxAPI deviceName memoryStatus queue commandBuffer renderer vendor numDrawCalls numInstances numTris capabilities], Shader::[name stages attributes blocks samplers], - Texture::[type usage format width height depth layerCount levelCount size samples flags], + Texture::[info viewInfo width height format size hash], Queue::[type], RenderPass::[hash], PipelineState::[shader primitive bindPoint inputState rasterizerState depthStencilState blendState renderPass], - InputAssembler::[vertexBuffers attributes indexBuffer indirectBuffer vertexCount firstVertex indexCount firstIndex vertexOffset instanceCount firstInstance attributesHash], + InputAssembler::[vertexBuffers attributes indexBuffer indirectBuffer attributesHash drawInfo vertexCount firstVertex indexCount firstIndex vertexOffset instanceCount firstInstance], Commanduffer::[type queue numDrawCalls numInstances numTris], - Context::[sharedContext/getSharedContext vsyncMode colorFormat depthStencilFormat], Framebuffer::[renderPass colorTextures depthStencilTexture], Buffer::[usage memUsage stride count size flags], - Sampler::[minFilter magFilter mipFilter addressU addressV addressW maxAnisotropy cmpFunc borderColor mipLODBias], + Sampler::[info], + Swapchain::[width height surfaceTransform colorTexture depthStencilTexture], GFXObject::[objectType objectID typedID] rename_functions = DepthStencilState::[getHash=hash], BlendState::[getHash=hash], - RasterizerState::[getHash=hash], - CommandBuffer::[bindDescriptorSetForJS=bindDescriptorSet beginRenderPassForJS=beginRenderPass], - Queue::[submitForJS=submit], - Device::[flushCommandsForJS=flushCommands] + RasterizerState::[getHash=hash] rename_classes =