2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/render/renderers/render-renderer.h>
22 #include <dali/graphics-api/graphics-types.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/internal/common/image-sampler.h>
25 #include <dali/internal/common/matrix-utils.h>
26 #include <dali/internal/common/memory-pool-object-allocator.h>
27 #include <dali/internal/event/rendering/texture-impl.h>
28 #include <dali/internal/render/common/render-instruction.h>
29 #include <dali/internal/render/data-providers/node-data-provider.h>
30 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
31 #include <dali/internal/render/renderers/pipeline-cache.h>
32 #include <dali/internal/render/renderers/render-sampler.h>
33 #include <dali/internal/render/renderers/render-texture.h>
34 #include <dali/internal/render/renderers/render-vertex-buffer.h>
35 #include <dali/internal/render/renderers/shader-cache.h>
36 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
37 #include <dali/internal/render/renderers/uniform-buffer-view.h>
38 #include <dali/internal/render/shaders/program.h>
39 #include <dali/internal/render/shaders/render-shader.h>
40 #include <dali/internal/update/common/uniform-map.h>
41 #include <dali/public-api/signals/render-callback.h>
43 namespace Dali::Internal
47 // Helper to get the property value getter by type
48 typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
49 constexpr FuncGetter GetPropertyValueGetter(Property::Type type)
53 case Property::BOOLEAN:
55 return FuncGetter(&PropertyInputImpl::GetBoolean);
57 case Property::INTEGER:
59 return FuncGetter(&PropertyInputImpl::GetInteger);
63 return FuncGetter(&PropertyInputImpl::GetFloat);
65 case Property::VECTOR2:
67 return FuncGetter(&PropertyInputImpl::GetVector2);
69 case Property::VECTOR3:
71 return FuncGetter(&PropertyInputImpl::GetVector3);
73 case Property::VECTOR4:
75 return FuncGetter(&PropertyInputImpl::GetVector4);
77 case Property::MATRIX3:
79 return FuncGetter(&PropertyInputImpl::GetMatrix3);
81 case Property::MATRIX:
83 return FuncGetter(&PropertyInputImpl::GetMatrix);
93 * Helper function that returns size of uniform datatypes based
96 constexpr int GetPropertyValueSizeForUniform(Property::Type type)
100 case Property::Type::BOOLEAN:
104 case Property::Type::FLOAT:
106 return sizeof(float);
108 case Property::Type::INTEGER:
112 case Property::Type::VECTOR2:
114 return sizeof(Vector2);
116 case Property::Type::VECTOR3:
118 return sizeof(Vector3);
120 case Property::Type::VECTOR4:
122 return sizeof(Vector4);
124 case Property::Type::MATRIX3:
126 return sizeof(Matrix3);
128 case Property::Type::MATRIX:
130 return sizeof(Matrix);
140 * Helper function to calculate the correct alignment of data for uniform buffers
141 * @param dataSize size of uniform buffer
142 * @return aligned offset of data
144 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
146 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
150 * @brief Store latest bound RenderGeometry, and help that we can skip duplicated vertex attributes bind.
152 * @param[in] geometry Current geometry to be used, or nullptr if render finished
153 * @return True if we can reuse latest bound vertex attributes. False otherwise.
155 inline bool ReuseLatestBoundVertexAttributes(const Render::Geometry* geometry)
157 static const Render::Geometry* gLatestVertexBoundGeometry = nullptr;
158 if(gLatestVertexBoundGeometry == geometry)
162 gLatestVertexBoundGeometry = geometry;
172 MemoryPoolObjectAllocator<Renderer> gRenderRendererMemoryPool;
175 void Renderer::PrepareCommandBuffer()
177 // Reset latest geometry informations, So we can bind the first of geometry.
178 ReuseLatestBoundVertexAttributes(nullptr);
180 // todo : Fill here as many caches as we can store for reduce the number of command buffers
183 RendererKey Renderer::NewKey(SceneGraph::RenderDataProvider* dataProvider,
184 Render::Geometry* geometry,
185 uint32_t blendingBitmask,
186 const Vector4& blendColor,
187 FaceCullingMode::Type faceCullingMode,
188 bool preMultipliedAlphaEnabled,
189 DepthWriteMode::Type depthWriteMode,
190 DepthTestMode::Type depthTestMode,
191 DepthFunction::Type depthFunction,
192 StencilParameters& stencilParameters)
194 void* ptr = gRenderRendererMemoryPool.AllocateRawThreadSafe();
195 auto key = gRenderRendererMemoryPool.GetKeyFromPtr(static_cast<Renderer*>(ptr));
197 // Use placement new to construct renderer.
198 new(ptr) Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
199 return RendererKey(key);
202 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
203 Render::Geometry* geometry,
204 uint32_t blendingBitmask,
205 const Vector4& blendColor,
206 FaceCullingMode::Type faceCullingMode,
207 bool preMultipliedAlphaEnabled,
208 DepthWriteMode::Type depthWriteMode,
209 DepthTestMode::Type depthTestMode,
210 DepthFunction::Type depthFunction,
211 StencilParameters& stencilParameters)
212 : mGraphicsController(nullptr),
213 mRenderDataProvider(dataProvider),
215 mProgramCache(nullptr),
216 mStencilParameters(stencilParameters),
218 mIndexedDrawFirstElement(0),
219 mIndexedDrawElementsCount(0),
220 mDepthFunction(depthFunction),
221 mFaceCullingMode(faceCullingMode),
222 mDepthWriteMode(depthWriteMode),
223 mDepthTestMode(depthTestMode),
224 mPremultipliedAlphaEnabled(preMultipliedAlphaEnabled),
225 mShaderChanged(false)
227 if(blendingBitmask != 0u)
229 mBlendingOptions.SetBitmask(blendingBitmask);
232 mBlendingOptions.SetBlendColor(blendColor);
235 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
237 mGraphicsController = &graphicsController;
238 mProgramCache = &programCache;
239 mShaderCache = &shaderCache;
240 mUniformBufferManager = &uniformBufferManager;
241 mPipelineCache = &pipelineCache;
244 Renderer::~Renderer() = default;
246 void Renderer::operator delete(void* ptr)
248 gRenderRendererMemoryPool.FreeThreadSafe(static_cast<Renderer*>(ptr));
251 Renderer* Renderer::Get(RendererKey::KeyType rendererKey)
253 return gRenderRendererMemoryPool.GetPtrFromKey(rendererKey);
256 void Renderer::SetGeometry(Render::Geometry* geometry)
258 mGeometry = geometry;
261 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
263 mDrawCommands.clear();
264 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
267 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
269 uint32_t textureUnit = 0;
271 auto textures(mRenderDataProvider->GetTextures());
272 auto samplers(mRenderDataProvider->GetSamplers());
274 std::vector<Graphics::TextureBinding> textureBindings;
276 if(textures != nullptr)
278 const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
279 textureBindings.reserve(texturesCount);
281 for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
283 if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
285 Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
286 // if the sampler exists,
287 // if it's default, delete the graphics object
288 // otherwise re-initialize it if dirty
290 const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
294 boundTextures.PushBack(graphicsTexture);
295 const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
296 textureBindings.push_back(textureBinding);
303 if(!textureBindings.empty())
305 commandBuffer.BindTextures(textureBindings);
309 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
311 mFaceCullingMode = mode;
314 void Renderer::SetBlendingBitMask(uint32_t bitmask)
316 mBlendingOptions.SetBitmask(bitmask);
319 void Renderer::SetBlendColor(const Vector4& color)
321 mBlendingOptions.SetBlendColor(color);
324 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
326 mIndexedDrawFirstElement = firstElement;
329 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
331 mIndexedDrawElementsCount = elementsCount;
334 void Renderer::EnablePreMultipliedAlpha(bool enable)
336 mPremultipliedAlphaEnabled = enable;
339 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
341 mDepthWriteMode = depthWriteMode;
344 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
346 mDepthTestMode = depthTestMode;
349 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
351 return mDepthWriteMode;
354 DepthTestMode::Type Renderer::GetDepthTestMode() const
356 return mDepthTestMode;
359 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
361 mDepthFunction = depthFunction;
364 DepthFunction::Type Renderer::GetDepthFunction() const
366 return mDepthFunction;
369 void Renderer::SetRenderMode(RenderMode::Type renderMode)
371 mStencilParameters.renderMode = renderMode;
374 RenderMode::Type Renderer::GetRenderMode() const
376 return mStencilParameters.renderMode;
379 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
381 mStencilParameters.stencilFunction = stencilFunction;
384 StencilFunction::Type Renderer::GetStencilFunction() const
386 return mStencilParameters.stencilFunction;
389 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
391 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
394 int Renderer::GetStencilFunctionMask() const
396 return mStencilParameters.stencilFunctionMask;
399 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
401 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
404 int Renderer::GetStencilFunctionReference() const
406 return mStencilParameters.stencilFunctionReference;
409 void Renderer::SetStencilMask(int stencilMask)
411 mStencilParameters.stencilMask = stencilMask;
414 int Renderer::GetStencilMask() const
416 return mStencilParameters.stencilMask;
419 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
421 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
424 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
426 return mStencilParameters.stencilOperationOnFail;
429 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
431 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
434 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
436 return mStencilParameters.stencilOperationOnZFail;
439 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
441 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
444 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
446 return mStencilParameters.stencilOperationOnZPass;
449 void Renderer::Upload()
451 mGeometry->Upload(*mGraphicsController);
454 bool Renderer::Render(Graphics::CommandBuffer& commandBuffer,
455 BufferIndex bufferIndex,
456 const SceneGraph::NodeDataProvider& node,
457 const Matrix& modelMatrix,
458 const Matrix& modelViewMatrix,
459 const Matrix& viewMatrix,
460 const Matrix& projectionMatrix,
463 Vector<Graphics::Texture*>& boundTextures,
464 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
467 // Before doing anything test if the call happens in the right queue
468 if(mDrawCommands.empty() && queueIndex > 0)
473 // Check if there is render callback
476 if(!mRenderCallbackInput)
478 mRenderCallbackInput = std::unique_ptr<RenderCallbackInput>(new RenderCallbackInput);
481 Graphics::DrawNativeInfo info{};
482 info.api = Graphics::DrawNativeAPI::GLES;
483 info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
484 info.userData = mRenderCallbackInput.get();
486 // Set storage for the context to be used
487 info.glesNativeInfo.eglSharedContextStoragePointer = &mRenderCallbackInput->eglContext;
488 info.reserved = nullptr;
490 auto& textureResources = mRenderCallback->GetTextureResources();
492 if(!textureResources.empty())
494 mRenderCallbackTextureBindings.clear();
495 mRenderCallbackInput->textureBindings.resize(textureResources.size());
497 for(auto& texture : textureResources)
499 auto& textureImpl = GetImplementation(texture);
500 auto graphicsTexture = textureImpl.GetRenderTextureKey()->GetGraphicsObject();
502 auto properties = mGraphicsController->GetTextureProperties(*graphicsTexture);
504 mRenderCallbackTextureBindings.emplace_back(graphicsTexture);
505 mRenderCallbackInput->textureBindings[i++] = properties.nativeHandle;
507 info.textureCount = mRenderCallbackTextureBindings.size();
508 info.textureList = mRenderCallbackTextureBindings.data();
511 // pass render callback input
512 mRenderCallbackInput->size = size;
513 mRenderCallbackInput->projection = projectionMatrix;
515 MatrixUtils::MultiplyProjectionMatrix(mRenderCallbackInput->mvp, modelViewMatrix, projectionMatrix);
518 commandBuffer.DrawNative(&info);
523 std::vector<DevelRenderer::DrawCommand*> commands;
524 for(auto& cmd : mDrawCommands)
526 if(cmd.queue == queueIndex)
528 commands.emplace_back(&cmd);
532 // Have commands but nothing to be drawn - abort
533 if(!mDrawCommands.empty() && commands.empty())
539 if(!mDrawCommands.empty())
541 blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
545 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
547 Program* program = Program::New(*mProgramCache,
549 *mGraphicsController);
552 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
556 // If program doesn't have Gfx program object assigned yet, prepare it.
557 if(!program->GetGraphicsProgramPtr())
559 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
560 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
561 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
563 Graphics::PipelineStage::VERTEX_SHADER,
564 shaderData->GetSourceMode());
566 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
568 Graphics::PipelineStage::FRAGMENT_SHADER,
569 shaderData->GetSourceMode());
571 std::vector<Graphics::ShaderState> shaderStates{
572 Graphics::ShaderState()
573 .SetShader(vertexShader)
574 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
575 Graphics::ShaderState()
576 .SetShader(fragmentShader)
577 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
579 auto createInfo = Graphics::ProgramCreateInfo();
580 createInfo.SetShaderState(shaderStates);
581 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
582 program->SetGraphicsProgram(std::move(graphicsProgram));
585 // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
586 auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
588 commandBuffer.BindPipeline(pipeline);
590 BindTextures(commandBuffer, boundTextures);
592 std::size_t nodeIndex = BuildUniformIndexMap(bufferIndex, node, size, *program);
594 WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size, nodeIndex);
596 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
597 // @todo We should detect this case much earlier to prevent unnecessary work
599 // Reuse latest bound vertex attributes location, or Bind buffers to attribute locations.
600 if(ReuseLatestBoundVertexAttributes(mGeometry) || mGeometry->BindVertexAttributes(commandBuffer))
602 if(mDrawCommands.empty())
604 drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
608 for(auto& cmd : commands)
610 drawn |= mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
616 // BindVertexAttributes failed. Reset cached geometry.
617 ReuseLatestBoundVertexAttributes(nullptr);
623 std::size_t Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
625 // Check if the map has changed
626 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
628 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
629 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetCollectedUniformMap();
630 const SceneGraph::UniformMap& uniformMapNode = node.GetNodeUniformMap();
634 // Usual case is to only have 1 node, however we do allow multiple nodes to reuse the same
635 // renderer, so we have to cache uniform map per render item (node / renderer pair).
637 // Specially, if node don't have uniformMap, we mark nodePtr as nullptr.
638 // So, all nodes without uniformMap will share same UniformIndexMap, contains only render data providers.
639 const auto nodePtr = uniformMapNode.Count() ? &node : nullptr;
641 const auto nodeChangeCounter = nodePtr ? uniformMapNode.GetChangeCounter() : 0;
642 const auto renderItemMapChangeCounter = uniformMap.GetChangeCounter();
644 auto iter = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
646 std::size_t renderItemMapIndex;
647 if(iter == mNodeIndexMap.end())
649 renderItemMapIndex = mUniformIndexMaps.size();
650 RenderItemLookup renderItemLookup;
651 renderItemLookup.node = nodePtr;
652 renderItemLookup.index = renderItemMapIndex;
653 renderItemLookup.nodeChangeCounter = nodeChangeCounter;
654 renderItemLookup.renderItemMapChangeCounter = renderItemMapChangeCounter;
655 mNodeIndexMap.emplace_back(renderItemLookup);
658 mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
662 renderItemMapIndex = iter->index;
664 updateMaps = (nodeChangeCounter != iter->nodeChangeCounter) ||
665 (renderItemMapChangeCounter != iter->renderItemMapChangeCounter) ||
666 (mUniformIndexMaps[renderItemMapIndex].size() == 0);
668 iter->nodeChangeCounter = nodeChangeCounter;
669 iter->renderItemMapChangeCounter = renderItemMapChangeCounter;
672 if(updateMaps || mShaderChanged)
674 // Reset shader pointer
675 mShaderChanged = false;
677 const uint32_t mapCount = uniformMap.Count();
678 const uint32_t mapNodeCount = uniformMapNode.Count();
680 mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
681 mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
683 // Copy uniform map into mUniformIndexMap
684 uint32_t mapIndex = 0;
685 for(; mapIndex < mapCount; ++mapIndex)
687 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMap.mUniformMap[mapIndex].propertyPtr;
688 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMap.mUniformMap[mapIndex].uniformName;
689 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMap.mUniformMap[mapIndex].uniformNameHash;
690 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
691 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMap.mUniformMap[mapIndex].arrayIndex;
694 for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
696 auto hash = uniformMapNode[nodeMapIndex].uniformNameHash;
697 auto& name = uniformMapNode[nodeMapIndex].uniformName;
699 for(uint32_t i = 0; i < mapCount; ++i)
701 if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
702 mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
704 mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
712 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
713 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
714 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
715 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
716 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
721 mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
723 return renderItemMapIndex;
726 void Renderer::WriteUniformBuffer(
727 BufferIndex bufferIndex,
728 Graphics::CommandBuffer& commandBuffer,
730 const SceneGraph::RenderInstruction& instruction,
731 const SceneGraph::NodeDataProvider& node,
732 const Matrix& modelMatrix,
733 const Matrix& modelViewMatrix,
734 const Matrix& viewMatrix,
735 const Matrix& projectionMatrix,
737 std::size_t nodeIndex)
740 uint32_t uboOffset{0u};
742 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
744 uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
746 // Create uniform buffer view from uniform buffer
747 Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
748 if(uniformBlockAllocationBytes)
750 auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
751 uboView = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
754 // update the uniform buffer
755 // pass shared UBO and offset, return new offset for next item to be used
756 // don't process bindings if there are no uniform buffers allocated
759 auto uboCount = reflection.GetUniformBlockCount();
760 mUniformBufferBindings.resize(uboCount);
762 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
764 mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
766 // Write default uniforms
767 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
768 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
769 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
770 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
772 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
773 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
775 Matrix modelViewProjectionMatrix(false);
776 MatrixUtils::MultiplyProjectionMatrix(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
777 WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
780 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
781 if(normalUniformInfo && !normalUniformInfo->name.empty())
783 Matrix3 normalMatrix(modelViewMatrix);
784 normalMatrix.Invert();
785 normalMatrix.Transpose();
786 WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
789 Vector4 finalColor; ///< Applied renderer's opacity color
790 const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
791 if(mPremultipliedAlphaEnabled)
793 const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
794 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
798 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
800 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
801 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
803 // Write uniforms from the uniform map
804 FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
806 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
807 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
809 commandBuffer.BindUniformBuffers(*bindings);
814 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
816 if(uniformInfo && !uniformInfo->name.empty())
818 WriteUniform(ubo, *uniformInfo, data);
825 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
827 WriteUniform(ubo, uniformInfo, &data, sizeof(T));
830 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
832 ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
835 void Renderer::FillUniformBuffer(Program& program,
836 const SceneGraph::RenderInstruction& instruction,
837 Render::UniformBufferView& ubo,
838 std::vector<Graphics::UniformBufferBinding>*& outBindings,
840 BufferIndex updateBufferIndex,
841 std::size_t nodeIndex)
843 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
844 auto uboCount = reflection.GetUniformBlockCount();
847 uint32_t dataOffset = offset;
848 for(auto i = 0u; i < uboCount; ++i)
850 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
851 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
853 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
854 mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
856 for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
857 end = mUniformIndexMaps[nodeIndex].end();
861 auto& uniform = *iter;
862 int arrayIndex = uniform.arrayIndex;
864 if(!uniform.uniformFunc)
866 auto uniformInfo = Graphics::UniformInfo{};
867 auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
868 uniform.uniformNameHash,
869 uniform.uniformNameHashNoArray,
872 uniform.uniformOffset = uniformInfo.offset;
873 uniform.uniformLocation = uniformInfo.location;
877 auto dst = ubo.GetOffset() + uniformInfo.offset;
878 const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
879 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
880 const auto func = GetPropertyValueGetter((*iter).propertyValue->GetType());
882 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
886 uniform.uniformSize = typeSize;
887 uniform.uniformFunc = func;
892 auto dst = ubo.GetOffset() + uniform.uniformOffset;
893 const auto typeSize = uniform.uniformSize;
894 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
895 const auto func = uniform.uniformFunc;
897 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
903 // write output bindings
904 outBindings = &mUniformBufferBindings;
910 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
912 sortAttributes.shader = &(mRenderDataProvider->GetShader());
913 sortAttributes.geometry = mGeometry;
916 void Renderer::SetShaderChanged(bool value)
918 mShaderChanged = value;
921 bool Renderer::Updated(BufferIndex bufferIndex)
923 if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged() || mRenderDataProvider->IsUpdated())
928 auto* textures = mRenderDataProvider->GetTextures();
931 for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
933 auto texture = *iter;
934 if(texture && texture->Updated())
943 Vector4 Renderer::GetVisualTransformedUpdateArea(BufferIndex bufferIndex, const Vector4& originalUpdateArea) const noexcept
945 return mRenderDataProvider->GetVisualTransformedUpdateArea(bufferIndex, originalUpdateArea);
948 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
950 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
951 const SceneGraph::NodeDataProvider& node,
954 // Prepare query info
955 PipelineCacheQueryInfo queryInfo{};
956 queryInfo.program = &program;
957 queryInfo.renderer = this;
958 queryInfo.geometry = mGeometry;
959 queryInfo.blendingEnabled = blend;
960 queryInfo.blendingOptions = &mBlendingOptions;
961 queryInfo.alphaPremultiplied = mPremultipliedAlphaEnabled;
962 queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
964 queryInfo.GenerateHash();
966 // Find or generate new pipeline.
967 auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
969 // should be never null?
970 return *pipelineResult.pipeline;
973 void Renderer::SetRenderCallback(RenderCallback* callback)
975 mRenderCallback = callback;
978 } // namespace Render
980 } // namespace Dali::Internal