Minor optimize during build uniform index maps
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/renderers/render-renderer.h>
20
21 // INTERNAL INCLUDES
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/render/common/render-instruction.h>
26 #include <dali/internal/render/data-providers/node-data-provider.h>
27 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
28 #include <dali/internal/render/renderers/pipeline-cache.h>
29 #include <dali/internal/render/renderers/render-sampler.h>
30 #include <dali/internal/render/renderers/render-texture.h>
31 #include <dali/internal/render/renderers/render-vertex-buffer.h>
32 #include <dali/internal/render/renderers/shader-cache.h>
33 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
34 #include <dali/internal/render/renderers/uniform-buffer-view.h>
35 #include <dali/internal/render/shaders/program.h>
36 #include <dali/internal/render/shaders/render-shader.h>
37 #include <dali/internal/update/common/uniform-map.h>
38 #include <dali/public-api/signals/render-callback.h>
39
40 namespace Dali::Internal
41 {
42 namespace
43 {
44 // Helper to get the property value getter by type
45 typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
46 constexpr FuncGetter GetPropertyValueGetter(Property::Type type)
47 {
48   switch(type)
49   {
50     case Property::BOOLEAN:
51     {
52       return FuncGetter(&PropertyInputImpl::GetBoolean);
53     }
54     case Property::INTEGER:
55     {
56       return FuncGetter(&PropertyInputImpl::GetInteger);
57     }
58     case Property::FLOAT:
59     {
60       return FuncGetter(&PropertyInputImpl::GetFloat);
61     }
62     case Property::VECTOR2:
63     {
64       return FuncGetter(&PropertyInputImpl::GetVector2);
65     }
66     case Property::VECTOR3:
67     {
68       return FuncGetter(&PropertyInputImpl::GetVector3);
69     }
70     case Property::VECTOR4:
71     {
72       return FuncGetter(&PropertyInputImpl::GetVector4);
73     }
74     case Property::MATRIX3:
75     {
76       return FuncGetter(&PropertyInputImpl::GetMatrix3);
77     }
78     case Property::MATRIX:
79     {
80       return FuncGetter(&PropertyInputImpl::GetMatrix);
81     }
82     default:
83     {
84       return nullptr;
85     }
86   }
87 }
88
89 /**
90  * Helper function that returns size of uniform datatypes based
91  * on property type.
92  */
93 constexpr int GetPropertyValueSizeForUniform(Property::Type type)
94 {
95   switch(type)
96   {
97     case Property::Type::BOOLEAN:
98     {
99       return sizeof(bool);
100     }
101     case Property::Type::FLOAT:
102     {
103       return sizeof(float);
104     }
105     case Property::Type::INTEGER:
106     {
107       return sizeof(int);
108     }
109     case Property::Type::VECTOR2:
110     {
111       return sizeof(Vector2);
112     }
113     case Property::Type::VECTOR3:
114     {
115       return sizeof(Vector3);
116     }
117     case Property::Type::VECTOR4:
118     {
119       return sizeof(Vector4);
120     }
121     case Property::Type::MATRIX3:
122     {
123       return sizeof(Matrix3);
124     }
125     case Property::Type::MATRIX:
126     {
127       return sizeof(Matrix);
128     }
129     default:
130     {
131       return 0;
132     }
133   };
134 }
135
136 /**
137  * Helper function to calculate the correct alignment of data for uniform buffers
138  * @param dataSize size of uniform buffer
139  * @return aligned offset of data
140  */
141 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
142 {
143   return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
144 }
145
146 } // namespace
147
148 namespace Render
149 {
150 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
151                         Render::Geometry*               geometry,
152                         uint32_t                        blendingBitmask,
153                         const Vector4&                  blendColor,
154                         FaceCullingMode::Type           faceCullingMode,
155                         bool                            preMultipliedAlphaEnabled,
156                         DepthWriteMode::Type            depthWriteMode,
157                         DepthTestMode::Type             depthTestMode,
158                         DepthFunction::Type             depthFunction,
159                         StencilParameters&              stencilParameters)
160 {
161   return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
162 }
163
164 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
165                    Render::Geometry*               geometry,
166                    uint32_t                        blendingBitmask,
167                    const Vector4&                  blendColor,
168                    FaceCullingMode::Type           faceCullingMode,
169                    bool                            preMultipliedAlphaEnabled,
170                    DepthWriteMode::Type            depthWriteMode,
171                    DepthTestMode::Type             depthTestMode,
172                    DepthFunction::Type             depthFunction,
173                    StencilParameters&              stencilParameters)
174 : mGraphicsController(nullptr),
175   mRenderDataProvider(dataProvider),
176   mGeometry(geometry),
177   mProgramCache(nullptr),
178   mStencilParameters(stencilParameters),
179   mBlendingOptions(),
180   mIndexedDrawFirstElement(0),
181   mIndexedDrawElementsCount(0),
182   mDepthFunction(depthFunction),
183   mFaceCullingMode(faceCullingMode),
184   mDepthWriteMode(depthWriteMode),
185   mDepthTestMode(depthTestMode),
186   mPremultipliedAlphaEnabled(preMultipliedAlphaEnabled),
187   mShaderChanged(false),
188   mUpdated(true)
189 {
190   if(blendingBitmask != 0u)
191   {
192     mBlendingOptions.SetBitmask(blendingBitmask);
193   }
194
195   mBlendingOptions.SetBlendColor(blendColor);
196 }
197
198 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
199 {
200   mGraphicsController   = &graphicsController;
201   mProgramCache         = &programCache;
202   mShaderCache          = &shaderCache;
203   mUniformBufferManager = &uniformBufferManager;
204   mPipelineCache        = &pipelineCache;
205 }
206
207 Renderer::~Renderer() = default;
208
209 void Renderer::SetGeometry(Render::Geometry* geometry)
210 {
211   mGeometry = geometry;
212   mUpdated  = true;
213 }
214 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
215 {
216   mDrawCommands.clear();
217   mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
218 }
219
220 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
221 {
222   uint32_t textureUnit = 0;
223
224   const Dali::Vector<Render::Texture*>* textures(mRenderDataProvider->GetTextures());
225   const Dali::Vector<Render::Sampler*>* samplers(mRenderDataProvider->GetSamplers());
226
227   std::vector<Graphics::TextureBinding> textureBindings;
228
229   if(textures != nullptr)
230   {
231     const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
232     textureBindings.reserve(texturesCount);
233
234     for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
235     {
236       if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
237       {
238         Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
239         // if the sampler exists,
240         //   if it's default, delete the graphics object
241         //   otherwise re-initialize it if dirty
242
243         const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
244                                                                               : nullptr)
245                                                             : nullptr;
246
247         boundTextures.PushBack(graphicsTexture);
248         const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
249         textureBindings.push_back(textureBinding);
250
251         ++textureUnit;
252       }
253     }
254   }
255
256   if(!textureBindings.empty())
257   {
258     commandBuffer.BindTextures(textureBindings);
259   }
260 }
261
262 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
263 {
264   mFaceCullingMode = mode;
265   mUpdated         = true;
266 }
267
268 void Renderer::SetBlendingBitMask(uint32_t bitmask)
269 {
270   mBlendingOptions.SetBitmask(bitmask);
271   mUpdated = true;
272 }
273
274 void Renderer::SetBlendColor(const Vector4& color)
275 {
276   mBlendingOptions.SetBlendColor(color);
277   mUpdated = true;
278 }
279
280 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
281 {
282   mIndexedDrawFirstElement = firstElement;
283   mUpdated                 = true;
284 }
285
286 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
287 {
288   mIndexedDrawElementsCount = elementsCount;
289   mUpdated                  = true;
290 }
291
292 void Renderer::EnablePreMultipliedAlpha(bool enable)
293 {
294   mPremultipliedAlphaEnabled = enable;
295   mUpdated                   = true;
296 }
297
298 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
299 {
300   mDepthWriteMode = depthWriteMode;
301   mUpdated        = true;
302 }
303
304 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
305 {
306   mDepthTestMode = depthTestMode;
307   mUpdated       = true;
308 }
309
310 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
311 {
312   return mDepthWriteMode;
313 }
314
315 DepthTestMode::Type Renderer::GetDepthTestMode() const
316 {
317   return mDepthTestMode;
318 }
319
320 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
321 {
322   mDepthFunction = depthFunction;
323   mUpdated       = true;
324 }
325
326 DepthFunction::Type Renderer::GetDepthFunction() const
327 {
328   return mDepthFunction;
329 }
330
331 void Renderer::SetRenderMode(RenderMode::Type renderMode)
332 {
333   mStencilParameters.renderMode = renderMode;
334   mUpdated                      = true;
335 }
336
337 RenderMode::Type Renderer::GetRenderMode() const
338 {
339   return mStencilParameters.renderMode;
340 }
341
342 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
343 {
344   mStencilParameters.stencilFunction = stencilFunction;
345   mUpdated                           = true;
346 }
347
348 StencilFunction::Type Renderer::GetStencilFunction() const
349 {
350   return mStencilParameters.stencilFunction;
351 }
352
353 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
354 {
355   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
356   mUpdated                               = true;
357 }
358
359 int Renderer::GetStencilFunctionMask() const
360 {
361   return mStencilParameters.stencilFunctionMask;
362 }
363
364 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
365 {
366   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
367   mUpdated                                    = true;
368 }
369
370 int Renderer::GetStencilFunctionReference() const
371 {
372   return mStencilParameters.stencilFunctionReference;
373 }
374
375 void Renderer::SetStencilMask(int stencilMask)
376 {
377   mStencilParameters.stencilMask = stencilMask;
378   mUpdated                       = true;
379 }
380
381 int Renderer::GetStencilMask() const
382 {
383   return mStencilParameters.stencilMask;
384 }
385
386 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
387 {
388   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
389   mUpdated                                  = true;
390 }
391
392 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
393 {
394   return mStencilParameters.stencilOperationOnFail;
395 }
396
397 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
398 {
399   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
400   mUpdated                                   = true;
401 }
402
403 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
404 {
405   return mStencilParameters.stencilOperationOnZFail;
406 }
407
408 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
409 {
410   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
411   mUpdated                                   = true;
412 }
413
414 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
415 {
416   return mStencilParameters.stencilOperationOnZPass;
417 }
418
419 void Renderer::Upload()
420 {
421   mGeometry->Upload(*mGraphicsController);
422 }
423
424 bool Renderer::Render(Graphics::CommandBuffer&                             commandBuffer,
425                       BufferIndex                                          bufferIndex,
426                       const SceneGraph::NodeDataProvider&                  node,
427                       const Matrix&                                        modelMatrix,
428                       const Matrix&                                        modelViewMatrix,
429                       const Matrix&                                        viewMatrix,
430                       const Matrix&                                        projectionMatrix,
431                       const Vector3&                                       size,
432                       bool                                                 blend,
433                       Vector<Graphics::Texture*>&                          boundTextures,
434                       const Dali::Internal::SceneGraph::RenderInstruction& instruction,
435                       uint32_t                                             queueIndex)
436 {
437   // Before doing anything test if the call happens in the right queue
438   if(mDrawCommands.empty() && queueIndex > 0)
439   {
440     return false;
441   }
442
443   // Check if there is render callback
444   if(mRenderCallback)
445   {
446     Graphics::DrawNativeInfo info{};
447     info.api      = Graphics::DrawNativeAPI::GLES;
448     info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
449     info.userData = &mRenderCallbackInput;
450     info.reserved = nullptr;
451
452     // pass render callback input
453     mRenderCallbackInput.size       = size;
454     mRenderCallbackInput.projection = projectionMatrix;
455     Matrix::Multiply(mRenderCallbackInput.mvp, modelViewMatrix, projectionMatrix);
456
457     // submit draw
458     commandBuffer.DrawNative(&info);
459     return true;
460   }
461
462   // Prepare commands
463   std::vector<DevelRenderer::DrawCommand*> commands;
464   for(auto& cmd : mDrawCommands)
465   {
466     if(cmd.queue == queueIndex)
467     {
468       commands.emplace_back(&cmd);
469     }
470   }
471
472   // Have commands but nothing to be drawn - abort
473   if(!mDrawCommands.empty() && commands.empty())
474   {
475     return false;
476   }
477
478   // Set blending mode
479   if(!mDrawCommands.empty())
480   {
481     blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
482   }
483
484   // Create Program
485   ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
486
487   Program* program = Program::New(*mProgramCache,
488                                   shaderData,
489                                   *mGraphicsController);
490   if(!program)
491   {
492     DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
493     return false;
494   }
495
496   // If program doesn't have Gfx program object assigned yet, prepare it.
497   if(!program->GetGraphicsProgramPtr())
498   {
499     const std::vector<char>& vertShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
500     const std::vector<char>& fragShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
501     Dali::Graphics::Shader&  vertexShader = mShaderCache->GetShader(
502       vertShader,
503       Graphics::PipelineStage::VERTEX_SHADER,
504       shaderData->GetSourceMode());
505
506     Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
507       fragShader,
508       Graphics::PipelineStage::FRAGMENT_SHADER,
509       shaderData->GetSourceMode());
510
511     std::vector<Graphics::ShaderState> shaderStates{
512       Graphics::ShaderState()
513         .SetShader(vertexShader)
514         .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
515       Graphics::ShaderState()
516         .SetShader(fragmentShader)
517         .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
518
519     auto createInfo = Graphics::ProgramCreateInfo();
520     createInfo.SetShaderState(shaderStates);
521     auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
522     program->SetGraphicsProgram(std::move(graphicsProgram));
523   }
524
525   // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
526   auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
527
528   commandBuffer.BindPipeline(pipeline);
529
530   BindTextures(commandBuffer, boundTextures);
531
532   int nodeIndex = BuildUniformIndexMap(bufferIndex, node, size, *program);
533
534   WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size, nodeIndex);
535
536   bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
537                       // @todo We should detect this case much earlier to prevent unnecessary work
538
539   if(mDrawCommands.empty())
540   {
541     drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
542   }
543   else
544   {
545     for(auto& cmd : commands)
546     {
547       mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
548     }
549   }
550
551   mUpdated = false;
552   return drawn;
553 }
554
555 int Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
556 {
557   // Check if the map has changed
558   DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
559
560   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
561   const SceneGraph::CollectedUniformMap&    uniformMap             = uniformMapDataProvider.GetCollectedUniformMap();
562   const SceneGraph::UniformMap&             uniformMapNode         = node.GetNodeUniformMap();
563
564   bool updateMaps;
565
566   // Usual case is to only have 1 node, however we do allow multiple nodes to reuse the same
567   // renderer, so we have to cache uniform map per render item (node / renderer pair).
568
569   // Specially, if node don't have uniformMap, we mark nodePtr as nullptr.
570   // So, all nodes without uniformMap will share same UniformIndexMap, contains only render data providers.
571   const auto nodePtr = uniformMapNode.Count() ? &node : nullptr;
572
573   const auto nodeChangeCounter          = nodePtr ? uniformMapNode.GetChangeCounter() : 0;
574   const auto renderItemMapChangeCounter = uniformMap.GetChangeCounter();
575
576   auto iter = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
577
578   int renderItemMapIndex;
579   if(iter == mNodeIndexMap.end())
580   {
581     renderItemMapIndex = mUniformIndexMaps.size();
582     RenderItemLookup renderItemLookup;
583     renderItemLookup.node                       = nodePtr;
584     renderItemLookup.index                      = renderItemMapIndex;
585     renderItemLookup.nodeChangeCounter          = nodeChangeCounter;
586     renderItemLookup.renderItemMapChangeCounter = renderItemMapChangeCounter;
587     mNodeIndexMap.emplace_back(renderItemLookup);
588
589     updateMaps = true;
590     mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
591   }
592   else
593   {
594     renderItemMapIndex = iter->index;
595
596     updateMaps = (nodeChangeCounter != iter->nodeChangeCounter) ||
597                  (renderItemMapChangeCounter != iter->renderItemMapChangeCounter) ||
598                  (mUniformIndexMaps[renderItemMapIndex].size() == 0);
599
600     iter->nodeChangeCounter          = nodeChangeCounter;
601     iter->renderItemMapChangeCounter = renderItemMapChangeCounter;
602   }
603
604   if(updateMaps || mShaderChanged)
605   {
606     // Reset shader pointer
607     mShaderChanged = false;
608
609     const uint32_t mapCount     = uniformMap.Count();
610     const uint32_t mapNodeCount = uniformMapNode.Count();
611
612     mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
613     mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
614
615     // Copy uniform map into mUniformIndexMap
616     uint32_t mapIndex = 0;
617     for(; mapIndex < mapCount; ++mapIndex)
618     {
619       mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMap.mUniformMap[mapIndex].propertyPtr;
620       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMap.mUniformMap[mapIndex].uniformName;
621       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMap.mUniformMap[mapIndex].uniformNameHash;
622       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
623       mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMap.mUniformMap[mapIndex].arrayIndex;
624     }
625
626     for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
627     {
628       auto  hash = uniformMapNode[nodeMapIndex].uniformNameHash;
629       auto& name = uniformMapNode[nodeMapIndex].uniformName;
630       bool  found(false);
631       for(uint32_t i = 0; i < mapCount; ++i)
632       {
633         if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
634            mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
635         {
636           mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
637           found                                                  = true;
638           break;
639         }
640       }
641
642       if(!found)
643       {
644         mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMapNode[nodeMapIndex].propertyPtr;
645         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMapNode[nodeMapIndex].uniformName;
646         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMapNode[nodeMapIndex].uniformNameHash;
647         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
648         mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMapNode[nodeMapIndex].arrayIndex;
649         ++mapIndex;
650       }
651     }
652
653     mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
654   }
655   return renderItemMapIndex;
656 }
657
658 void Renderer::WriteUniformBuffer(
659   BufferIndex                          bufferIndex,
660   Graphics::CommandBuffer&             commandBuffer,
661   Program*                             program,
662   const SceneGraph::RenderInstruction& instruction,
663   const SceneGraph::NodeDataProvider&  node,
664   const Matrix&                        modelMatrix,
665   const Matrix&                        modelViewMatrix,
666   const Matrix&                        viewMatrix,
667   const Matrix&                        projectionMatrix,
668   const Vector3&                       size,
669   int                                  nodeIndex)
670 {
671   // Create the UBO
672   uint32_t uboOffset{0u};
673
674   auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
675
676   uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
677
678   // Create uniform buffer view from uniform buffer
679   Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
680   if(uniformBlockAllocationBytes)
681   {
682     auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
683     uboView          = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
684   }
685
686   // update the uniform buffer
687   // pass shared UBO and offset, return new offset for next item to be used
688   // don't process bindings if there are no uniform buffers allocated
689   if(uboView)
690   {
691     auto uboCount = reflection.GetUniformBlockCount();
692     mUniformBufferBindings.resize(uboCount);
693
694     std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
695
696     mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
697
698     // Write default uniforms
699     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
700     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
701     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
702     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
703
704     auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
705     if(mvpUniformInfo && !mvpUniformInfo->name.empty())
706     {
707       Matrix modelViewProjectionMatrix(false);
708       Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
709       WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
710     }
711
712     auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
713     if(normalUniformInfo && !normalUniformInfo->name.empty())
714     {
715       Matrix3 normalMatrix(modelViewMatrix);
716       normalMatrix.Invert();
717       normalMatrix.Transpose();
718       WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
719     }
720
721     Vector4        finalColor;                               ///< Applied renderer's opacity color
722     const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
723     if(mPremultipliedAlphaEnabled)
724     {
725       const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
726       finalColor         = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
727     }
728     else
729     {
730       finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
731     }
732     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
733     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
734
735     // Write uniforms from the uniform map
736     FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
737
738     // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
739     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
740
741     commandBuffer.BindUniformBuffers(*bindings);
742   }
743 }
744
745 template<class T>
746 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
747 {
748   if(uniformInfo && !uniformInfo->name.empty())
749   {
750     WriteUniform(ubo, *uniformInfo, data);
751     return true;
752   }
753   return false;
754 }
755
756 template<class T>
757 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
758 {
759   WriteUniform(ubo, uniformInfo, &data, sizeof(T));
760 }
761
762 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
763 {
764   ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
765 }
766
767 void Renderer::FillUniformBuffer(Program&                                      program,
768                                  const SceneGraph::RenderInstruction&          instruction,
769                                  Render::UniformBufferView&                    ubo,
770                                  std::vector<Graphics::UniformBufferBinding>*& outBindings,
771                                  uint32_t&                                     offset,
772                                  BufferIndex                                   updateBufferIndex,
773                                  int                                           nodeIndex)
774 {
775   auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
776   auto  uboCount   = reflection.GetUniformBlockCount();
777
778   // Setup bindings
779   uint32_t dataOffset = offset;
780   for(auto i = 0u; i < uboCount; ++i)
781   {
782     mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
783     mUniformBufferBindings[i].binding  = reflection.GetUniformBlockBinding(i);
784
785     dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
786     mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
787
788     for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
789              end  = mUniformIndexMaps[nodeIndex].end();
790         iter != end;
791         ++iter)
792     {
793       auto& uniform    = *iter;
794       int   arrayIndex = uniform.arrayIndex;
795
796       if(!uniform.uniformFunc)
797       {
798         auto uniformInfo  = Graphics::UniformInfo{};
799         auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
800                                                uniform.uniformNameHash,
801                                                uniform.uniformNameHashNoArray,
802                                                uniformInfo);
803
804         uniform.uniformOffset   = uniformInfo.offset;
805         uniform.uniformLocation = uniformInfo.location;
806
807         if(uniformFound)
808         {
809           auto       dst      = ubo.GetOffset() + uniformInfo.offset;
810           const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
811           const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
812           const auto func     = GetPropertyValueGetter((*iter).propertyValue->GetType());
813
814           ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
815                     typeSize,
816                     dest);
817
818           uniform.uniformSize = typeSize;
819           uniform.uniformFunc = func;
820         }
821       }
822       else
823       {
824         auto       dst      = ubo.GetOffset() + uniform.uniformOffset;
825         const auto typeSize = uniform.uniformSize;
826         const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
827         const auto func     = uniform.uniformFunc;
828
829         ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
830                   typeSize,
831                   dest);
832       }
833     }
834   }
835   // write output bindings
836   outBindings = &mUniformBufferBindings;
837
838   // Update offset
839   offset = dataOffset;
840 }
841
842 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
843 {
844   sortAttributes.shader   = &(mRenderDataProvider->GetShader());
845   sortAttributes.geometry = mGeometry;
846 }
847
848 void Renderer::SetShaderChanged(bool value)
849 {
850   mShaderChanged = value;
851 }
852
853 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
854 {
855   if(mUpdated)
856   {
857     mUpdated = false;
858     return true;
859   }
860
861   if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged())
862   {
863     return true;
864   }
865
866   auto* textures = mRenderDataProvider->GetTextures();
867   if(textures)
868   {
869     for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
870     {
871       auto texture = *iter;
872       if(texture && texture->IsNativeImage())
873       {
874         return true;
875       }
876     }
877   }
878
879   // Hash the property values. If the values are different, then rendering is required.
880   uint64_t                      hash           = 0xc70f6907UL;
881   const SceneGraph::UniformMap& uniformMapNode = node->GetNodeUniformMap();
882   for(uint32_t i = 0u, count = uniformMapNode.Count(); i < count; ++i)
883   {
884     hash = uniformMapNode[i].propertyPtr->Hash(bufferIndex, hash);
885   }
886
887   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
888   const SceneGraph::CollectedUniformMap&    collectedUniformMap    = uniformMapDataProvider.GetCollectedUniformMap();
889   for(uint32_t i = 0u, count = collectedUniformMap.Count(); i < count; ++i)
890   {
891     hash = collectedUniformMap.mUniformMap[i].propertyPtr->Hash(bufferIndex, hash);
892   }
893
894   if(mUniformsHash != hash)
895   {
896     mUniformsHash = hash;
897     return true;
898   }
899
900   return false;
901 }
902
903 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
904   Program&                                             program,
905   const Dali::Internal::SceneGraph::RenderInstruction& instruction,
906   const SceneGraph::NodeDataProvider&                  node,
907   bool                                                 blend)
908 {
909   if(mGeometry->AttributesChanged())
910   {
911     mUpdated = true;
912   }
913
914   // Prepare query info
915   PipelineCacheQueryInfo queryInfo{};
916   queryInfo.program               = &program;
917   queryInfo.renderer              = this;
918   queryInfo.geometry              = mGeometry;
919   queryInfo.blendingEnabled       = blend;
920   queryInfo.blendingOptions       = &mBlendingOptions;
921   queryInfo.alphaPremultiplied    = mPremultipliedAlphaEnabled;
922   queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
923
924   auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
925
926   // should be never null?
927   return *pipelineResult.pipeline;
928 }
929
930 void Renderer::SetRenderCallback(RenderCallback* callback)
931 {
932   mRenderCallback = callback;
933 }
934
935 } // namespace Render
936
937 } // namespace Dali::Internal