40490fb81438a675a20ebf5f4f2af4207fb92e98
[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   mUniformIndexMap(),
179   mUniformsHash(),
180   mStencilParameters(stencilParameters),
181   mBlendingOptions(),
182   mIndexedDrawFirstElement(0),
183   mIndexedDrawElementsCount(0),
184   mDepthFunction(depthFunction),
185   mFaceCullingMode(faceCullingMode),
186   mDepthWriteMode(depthWriteMode),
187   mDepthTestMode(depthTestMode),
188   mPremultipliedAlphaEnabled(preMultipliedAlphaEnabled),
189   mShaderChanged(false),
190   mUpdated(true)
191 {
192   if(blendingBitmask != 0u)
193   {
194     mBlendingOptions.SetBitmask(blendingBitmask);
195   }
196
197   mBlendingOptions.SetBlendColor(blendColor);
198 }
199
200 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
201 {
202   mGraphicsController   = &graphicsController;
203   mProgramCache         = &programCache;
204   mShaderCache          = &shaderCache;
205   mUniformBufferManager = &uniformBufferManager;
206   mPipelineCache        = &pipelineCache;
207 }
208
209 Renderer::~Renderer() = default;
210
211 void Renderer::SetGeometry(Render::Geometry* geometry)
212 {
213   mGeometry = geometry;
214   mUpdated  = true;
215 }
216 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
217 {
218   mDrawCommands.clear();
219   mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
220 }
221
222 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
223 {
224   uint32_t textureUnit = 0;
225
226   const Dali::Vector<Render::Texture*>* textures(mRenderDataProvider->GetTextures());
227   const Dali::Vector<Render::Sampler*>* samplers(mRenderDataProvider->GetSamplers());
228
229   std::vector<Graphics::TextureBinding> textureBindings;
230
231   if(textures != nullptr)
232   {
233     const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
234     textureBindings.reserve(texturesCount);
235
236     for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
237     {
238       if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
239       {
240         Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
241         // if the sampler exists,
242         //   if it's default, delete the graphics object
243         //   otherwise re-initialize it if dirty
244
245         const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
246                                                                               : nullptr)
247                                                             : nullptr;
248
249         boundTextures.PushBack(graphicsTexture);
250         const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
251         textureBindings.push_back(textureBinding);
252
253         ++textureUnit;
254       }
255     }
256   }
257
258   if(!textureBindings.empty())
259   {
260     commandBuffer.BindTextures(textureBindings);
261   }
262 }
263
264 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
265 {
266   mFaceCullingMode = mode;
267   mUpdated         = true;
268 }
269
270 void Renderer::SetBlendingBitMask(uint32_t bitmask)
271 {
272   mBlendingOptions.SetBitmask(bitmask);
273   mUpdated = true;
274 }
275
276 void Renderer::SetBlendColor(const Vector4& color)
277 {
278   mBlendingOptions.SetBlendColor(color);
279   mUpdated = true;
280 }
281
282 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
283 {
284   mIndexedDrawFirstElement = firstElement;
285   mUpdated                 = true;
286 }
287
288 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
289 {
290   mIndexedDrawElementsCount = elementsCount;
291   mUpdated                  = true;
292 }
293
294 void Renderer::EnablePreMultipliedAlpha(bool enable)
295 {
296   mPremultipliedAlphaEnabled = enable;
297   mUpdated                   = true;
298 }
299
300 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
301 {
302   mDepthWriteMode = depthWriteMode;
303   mUpdated        = true;
304 }
305
306 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
307 {
308   mDepthTestMode = depthTestMode;
309   mUpdated       = true;
310 }
311
312 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
313 {
314   return mDepthWriteMode;
315 }
316
317 DepthTestMode::Type Renderer::GetDepthTestMode() const
318 {
319   return mDepthTestMode;
320 }
321
322 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
323 {
324   mDepthFunction = depthFunction;
325   mUpdated       = true;
326 }
327
328 DepthFunction::Type Renderer::GetDepthFunction() const
329 {
330   return mDepthFunction;
331 }
332
333 void Renderer::SetRenderMode(RenderMode::Type renderMode)
334 {
335   mStencilParameters.renderMode = renderMode;
336   mUpdated                      = true;
337 }
338
339 RenderMode::Type Renderer::GetRenderMode() const
340 {
341   return mStencilParameters.renderMode;
342 }
343
344 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
345 {
346   mStencilParameters.stencilFunction = stencilFunction;
347   mUpdated                           = true;
348 }
349
350 StencilFunction::Type Renderer::GetStencilFunction() const
351 {
352   return mStencilParameters.stencilFunction;
353 }
354
355 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
356 {
357   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
358   mUpdated                               = true;
359 }
360
361 int Renderer::GetStencilFunctionMask() const
362 {
363   return mStencilParameters.stencilFunctionMask;
364 }
365
366 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
367 {
368   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
369   mUpdated                                    = true;
370 }
371
372 int Renderer::GetStencilFunctionReference() const
373 {
374   return mStencilParameters.stencilFunctionReference;
375 }
376
377 void Renderer::SetStencilMask(int stencilMask)
378 {
379   mStencilParameters.stencilMask = stencilMask;
380   mUpdated                       = true;
381 }
382
383 int Renderer::GetStencilMask() const
384 {
385   return mStencilParameters.stencilMask;
386 }
387
388 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
389 {
390   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
391   mUpdated                                  = true;
392 }
393
394 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
395 {
396   return mStencilParameters.stencilOperationOnFail;
397 }
398
399 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
400 {
401   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
402   mUpdated                                   = true;
403 }
404
405 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
406 {
407   return mStencilParameters.stencilOperationOnZFail;
408 }
409
410 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
411 {
412   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
413   mUpdated                                   = true;
414 }
415
416 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
417 {
418   return mStencilParameters.stencilOperationOnZPass;
419 }
420
421 void Renderer::Upload()
422 {
423   mGeometry->Upload(*mGraphicsController);
424 }
425
426 bool Renderer::Render(Graphics::CommandBuffer&                             commandBuffer,
427                       BufferIndex                                          bufferIndex,
428                       const SceneGraph::NodeDataProvider&                  node,
429                       const Matrix&                                        modelMatrix,
430                       const Matrix&                                        modelViewMatrix,
431                       const Matrix&                                        viewMatrix,
432                       const Matrix&                                        projectionMatrix,
433                       const Vector3&                                       size,
434                       bool                                                 blend,
435                       Vector<Graphics::Texture*>&                          boundTextures,
436                       const Dali::Internal::SceneGraph::RenderInstruction& instruction,
437                       uint32_t                                             queueIndex)
438 {
439   // Before doing anything test if the call happens in the right queue
440   if(mDrawCommands.empty() && queueIndex > 0)
441   {
442     return false;
443   }
444
445   // Check if there is render callback
446   if(mRenderCallback)
447   {
448     Graphics::DrawNativeInfo info{};
449     info.api      = Graphics::DrawNativeAPI::GLES;
450     info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
451     info.userData = &mRenderCallbackInput;
452     info.reserved = nullptr;
453
454     // pass render callback input
455     mRenderCallbackInput.size       = size;
456     mRenderCallbackInput.projection = projectionMatrix;
457     Matrix::Multiply(mRenderCallbackInput.mvp, modelViewMatrix, projectionMatrix);
458
459     // submit draw
460     commandBuffer.DrawNative(&info);
461     return true;
462   }
463
464   // Prepare commands
465   std::vector<DevelRenderer::DrawCommand*> commands;
466   for(auto& cmd : mDrawCommands)
467   {
468     if(cmd.queue == queueIndex)
469     {
470       commands.emplace_back(&cmd);
471     }
472   }
473
474   // Have commands but nothing to be drawn - abort
475   if(!mDrawCommands.empty() && commands.empty())
476   {
477     return false;
478   }
479
480   // Set blending mode
481   if(!mDrawCommands.empty())
482   {
483     blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
484   }
485
486   // Create Program
487   ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
488
489   Program* program = Program::New(*mProgramCache,
490                                   shaderData,
491                                   *mGraphicsController);
492   if(!program)
493   {
494     DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
495     return false;
496   }
497
498   // If program doesn't have Gfx program object assigned yet, prepare it.
499   if(!program->GetGraphicsProgramPtr())
500   {
501     const std::vector<char>& vertShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
502     const std::vector<char>& fragShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
503     Dali::Graphics::Shader&  vertexShader = mShaderCache->GetShader(
504       vertShader,
505       Graphics::PipelineStage::VERTEX_SHADER,
506       shaderData->GetSourceMode());
507
508     Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
509       fragShader,
510       Graphics::PipelineStage::FRAGMENT_SHADER,
511       shaderData->GetSourceMode());
512
513     std::vector<Graphics::ShaderState> shaderStates{
514       Graphics::ShaderState()
515         .SetShader(vertexShader)
516         .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
517       Graphics::ShaderState()
518         .SetShader(fragmentShader)
519         .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
520
521     auto createInfo = Graphics::ProgramCreateInfo();
522     createInfo.SetShaderState(shaderStates);
523     auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
524     program->SetGraphicsProgram(std::move(graphicsProgram));
525   }
526
527   // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
528   auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
529
530   commandBuffer.BindPipeline(pipeline);
531
532   BindTextures(commandBuffer, boundTextures);
533
534   BuildUniformIndexMap(bufferIndex, node, size, *program);
535
536   WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
537
538   bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
539                       // @todo We should detect this case much earlier to prevent unnecessary work
540
541   if(mDrawCommands.empty())
542   {
543     drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
544   }
545   else
546   {
547     for(auto& cmd : commands)
548     {
549       mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
550     }
551   }
552
553   mUpdated = false;
554   return drawn;
555 }
556
557 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
558 {
559   // Check if the map has changed
560   DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
561
562   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
563
564   if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
565      node.GetUniformMapChanged(bufferIndex) ||
566      mUniformIndexMap.Count() == 0 ||
567      mShaderChanged)
568   {
569     // Reset shader pointer
570     mShaderChanged = false;
571
572     const SceneGraph::CollectedUniformMap& uniformMap     = uniformMapDataProvider.GetUniformMap(bufferIndex);
573     const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
574
575     const uint32_t mapCount     = uniformMap.Count();
576     const uint32_t mapNodeCount = uniformMapNode.Count();
577
578     mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
579     mUniformIndexMap.Resize(mapCount + mapNodeCount);
580
581     // Copy uniform map into mUniformIndexMap
582     uint32_t mapIndex = 0;
583     for(; mapIndex < mapCount; ++mapIndex)
584     {
585       mUniformIndexMap[mapIndex].propertyValue          = uniformMap[mapIndex].propertyPtr;
586       mUniformIndexMap[mapIndex].uniformName            = uniformMap[mapIndex].uniformName;
587       mUniformIndexMap[mapIndex].uniformNameHash        = uniformMap[mapIndex].uniformNameHash;
588       mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
589       mUniformIndexMap[mapIndex].arrayIndex             = uniformMap[mapIndex].arrayIndex;
590     }
591
592     for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
593     {
594       auto  hash = uniformMapNode[nodeMapIndex].uniformNameHash;
595       auto& name = uniformMapNode[nodeMapIndex].uniformName;
596       bool  found(false);
597       for(uint32_t i = 0; i < mapCount; ++i)
598       {
599         if(mUniformIndexMap[i].uniformNameHash == hash &&
600            mUniformIndexMap[i].uniformName == name)
601         {
602           mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
603           found                             = true;
604           break;
605         }
606       }
607
608       if(!found)
609       {
610         mUniformIndexMap[mapIndex].propertyValue          = uniformMapNode[nodeMapIndex].propertyPtr;
611         mUniformIndexMap[mapIndex].uniformName            = uniformMapNode[nodeMapIndex].uniformName;
612         mUniformIndexMap[mapIndex].uniformNameHash        = uniformMapNode[nodeMapIndex].uniformNameHash;
613         mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
614         mUniformIndexMap[mapIndex].arrayIndex             = uniformMapNode[nodeMapIndex].arrayIndex;
615         ++mapIndex;
616       }
617     }
618
619     mUniformIndexMap.Resize(mapIndex);
620   }
621 }
622
623 void Renderer::WriteUniformBuffer(
624   BufferIndex                          bufferIndex,
625   Graphics::CommandBuffer&             commandBuffer,
626   Program*                             program,
627   const SceneGraph::RenderInstruction& instruction,
628   const SceneGraph::NodeDataProvider&  node,
629   const Matrix&                        modelMatrix,
630   const Matrix&                        modelViewMatrix,
631   const Matrix&                        viewMatrix,
632   const Matrix&                        projectionMatrix,
633   const Vector3&                       size)
634 {
635   // Create the UBO
636   uint32_t uboOffset{0u};
637
638   auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
639
640   uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
641
642   // Create uniform buffer view from uniform buffer
643   Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
644   if(uniformBlockAllocationBytes)
645   {
646     auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
647     uboView          = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
648   }
649
650   // update the uniform buffer
651   // pass shared UBO and offset, return new offset for next item to be used
652   // don't process bindings if there are no uniform buffers allocated
653   if(uboView)
654   {
655     auto uboCount = reflection.GetUniformBlockCount();
656     mUniformBufferBindings.resize(uboCount);
657
658     std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
659
660     mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
661
662     // Write default uniforms
663     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
664     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
665     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
666     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
667
668     auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
669     if(mvpUniformInfo && !mvpUniformInfo->name.empty())
670     {
671       Matrix modelViewProjectionMatrix(false);
672       Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
673       WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
674     }
675
676     auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
677     if(normalUniformInfo && !normalUniformInfo->name.empty())
678     {
679       Matrix3 normalMatrix(modelViewMatrix);
680       normalMatrix.Invert();
681       normalMatrix.Transpose();
682       WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
683     }
684
685     Vector4        finalColor;                               ///< Applied renderer's opacity color
686     const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
687     if(mPremultipliedAlphaEnabled)
688     {
689       const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
690       finalColor         = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
691     }
692     else
693     {
694       finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
695     }
696     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
697     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
698
699     // Write uniforms from the uniform map
700     FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex);
701
702     // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
703     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
704
705     commandBuffer.BindUniformBuffers(*bindings);
706   }
707 }
708
709 template<class T>
710 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
711 {
712   if(uniformInfo && !uniformInfo->name.empty())
713   {
714     WriteUniform(ubo, *uniformInfo, data);
715     return true;
716   }
717   return false;
718 }
719
720 template<class T>
721 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
722 {
723   WriteUniform(ubo, uniformInfo, &data, sizeof(T));
724 }
725
726 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
727 {
728   ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
729 }
730
731 void Renderer::FillUniformBuffer(Program&                                      program,
732                                  const SceneGraph::RenderInstruction&          instruction,
733                                  Render::UniformBufferView&                    ubo,
734                                  std::vector<Graphics::UniformBufferBinding>*& outBindings,
735                                  uint32_t&                                     offset,
736                                  BufferIndex                                   updateBufferIndex)
737 {
738   auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
739   auto  uboCount   = reflection.GetUniformBlockCount();
740
741   // Setup bindings
742   uint32_t dataOffset = offset;
743   for(auto i = 0u; i < uboCount; ++i)
744   {
745     mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
746     mUniformBufferBindings[i].binding  = reflection.GetUniformBlockBinding(i);
747
748     dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
749     mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
750
751     for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
752                                        end  = mUniformIndexMap.End();
753         iter != end;
754         ++iter)
755     {
756       auto& uniform    = *iter;
757       int   arrayIndex = uniform.arrayIndex;
758
759       if(!uniform.uniformFunc)
760       {
761         auto uniformInfo  = Graphics::UniformInfo{};
762         auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
763                                                uniform.uniformNameHash,
764                                                uniform.uniformNameHashNoArray,
765                                                uniformInfo);
766
767         uniform.uniformOffset   = uniformInfo.offset;
768         uniform.uniformLocation = uniformInfo.location;
769
770         if(uniformFound)
771         {
772           auto       dst      = ubo.GetOffset() + uniformInfo.offset;
773           const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
774           const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
775           const auto func     = GetPropertyValueGetter((*iter).propertyValue->GetType());
776
777           ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
778                     typeSize,
779                     dest);
780
781           uniform.uniformSize = typeSize;
782           uniform.uniformFunc = func;
783         }
784       }
785       else
786       {
787         auto       dst      = ubo.GetOffset() + uniform.uniformOffset;
788         const auto typeSize = uniform.uniformSize;
789         const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
790         const auto func     = uniform.uniformFunc;
791
792         ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
793                   typeSize,
794                   dest);
795       }
796     }
797   }
798   // write output bindings
799   outBindings = &mUniformBufferBindings;
800
801   // Update offset
802   offset = dataOffset;
803 }
804
805 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
806 {
807   sortAttributes.shader   = &(mRenderDataProvider->GetShader());
808   sortAttributes.geometry = mGeometry;
809 }
810
811 void Renderer::SetShaderChanged(bool value)
812 {
813   mShaderChanged = value;
814 }
815
816 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
817 {
818   if(mUpdated)
819   {
820     mUpdated = false;
821     return true;
822   }
823
824   if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged())
825   {
826     return true;
827   }
828
829   auto* textures = mRenderDataProvider->GetTextures();
830   if(textures)
831   {
832     for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
833     {
834       auto texture = *iter;
835       if(texture && texture->IsNativeImage())
836       {
837         return true;
838       }
839     }
840   }
841
842   uint64_t                               hash           = 0xc70f6907UL;
843   const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
844   for(const auto& uniformProperty : uniformMapNode)
845   {
846     hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
847   }
848
849   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
850   const SceneGraph::CollectedUniformMap&    uniformMap             = uniformMapDataProvider.GetUniformMap(bufferIndex);
851   for(const auto& uniformProperty : uniformMap)
852   {
853     hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
854   }
855
856   if(mUniformsHash != hash)
857   {
858     mUniformsHash = hash;
859     return true;
860   }
861
862   return false;
863 }
864
865 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
866   Program&                                             program,
867   const Dali::Internal::SceneGraph::RenderInstruction& instruction,
868   const SceneGraph::NodeDataProvider&                  node,
869   bool                                                 blend)
870 {
871   if(mGeometry->AttributesChanged())
872   {
873     mUpdated = true;
874   }
875
876   // Prepare query info
877   PipelineCacheQueryInfo queryInfo{};
878   queryInfo.program               = &program;
879   queryInfo.renderer              = this;
880   queryInfo.geometry              = mGeometry;
881   queryInfo.blendingEnabled       = blend;
882   queryInfo.blendingOptions       = &mBlendingOptions;
883   queryInfo.alphaPremultiplied    = mPremultipliedAlphaEnabled;
884   queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
885
886   auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
887
888   // should be never null?
889   return *pipelineResult.pipeline;
890 }
891
892 void Renderer::SetRenderCallback(RenderCallback* callback)
893 {
894   mRenderCallback = callback;
895 }
896
897 } // namespace Render
898
899 } // namespace Dali::Internal