Simplifying UniformMap updating
[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   const void* nodePtr = static_cast<const void*>(&node);
570   auto        iter    = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
571
572   int renderItemMapIndex;
573   if(iter == mNodeIndexMap.end())
574   {
575     renderItemMapIndex = mUniformIndexMaps.size();
576     RenderItemLookup renderItemLookup;
577     renderItemLookup.node                       = &node;
578     renderItemLookup.index                      = renderItemMapIndex;
579     renderItemLookup.nodeChangeCounter          = uniformMapNode.GetChangeCounter();
580     renderItemLookup.renderItemMapChangeCounter = uniformMap.GetChangeCounter();
581     mNodeIndexMap.emplace_back(renderItemLookup);
582
583     updateMaps = true;
584     mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
585   }
586   else
587   {
588     renderItemMapIndex = iter->index;
589
590     updateMaps = (uniformMapNode.GetChangeCounter() != iter->nodeChangeCounter) ||
591                  (uniformMap.GetChangeCounter() != iter->renderItemMapChangeCounter) ||
592                  (mUniformIndexMaps[renderItemMapIndex].size() == 0);
593
594     iter->nodeChangeCounter          = uniformMapNode.GetChangeCounter();
595     iter->renderItemMapChangeCounter = uniformMap.GetChangeCounter();
596   }
597
598   if(updateMaps || mShaderChanged)
599   {
600     // Reset shader pointer
601     mShaderChanged = false;
602
603     const uint32_t mapCount     = uniformMap.Count();
604     const uint32_t mapNodeCount = uniformMapNode.Count();
605
606     mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
607     mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
608
609     // Copy uniform map into mUniformIndexMap
610     uint32_t mapIndex = 0;
611     for(; mapIndex < mapCount; ++mapIndex)
612     {
613       mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMap.mUniformMap[mapIndex].propertyPtr;
614       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMap.mUniformMap[mapIndex].uniformName;
615       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMap.mUniformMap[mapIndex].uniformNameHash;
616       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
617       mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMap.mUniformMap[mapIndex].arrayIndex;
618     }
619
620     for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
621     {
622       auto  hash = uniformMapNode[nodeMapIndex].uniformNameHash;
623       auto& name = uniformMapNode[nodeMapIndex].uniformName;
624       bool  found(false);
625       for(uint32_t i = 0; i < mapCount; ++i)
626       {
627         if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
628            mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
629         {
630           mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
631           found                                                  = true;
632           break;
633         }
634       }
635
636       if(!found)
637       {
638         mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMapNode[nodeMapIndex].propertyPtr;
639         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMapNode[nodeMapIndex].uniformName;
640         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMapNode[nodeMapIndex].uniformNameHash;
641         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
642         mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMapNode[nodeMapIndex].arrayIndex;
643         ++mapIndex;
644       }
645     }
646
647     mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
648   }
649   return renderItemMapIndex;
650 }
651
652 void Renderer::WriteUniformBuffer(
653   BufferIndex                          bufferIndex,
654   Graphics::CommandBuffer&             commandBuffer,
655   Program*                             program,
656   const SceneGraph::RenderInstruction& instruction,
657   const SceneGraph::NodeDataProvider&  node,
658   const Matrix&                        modelMatrix,
659   const Matrix&                        modelViewMatrix,
660   const Matrix&                        viewMatrix,
661   const Matrix&                        projectionMatrix,
662   const Vector3&                       size,
663   int                                  nodeIndex)
664 {
665   // Create the UBO
666   uint32_t uboOffset{0u};
667
668   auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
669
670   uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
671
672   // Create uniform buffer view from uniform buffer
673   Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
674   if(uniformBlockAllocationBytes)
675   {
676     auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
677     uboView          = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
678   }
679
680   // update the uniform buffer
681   // pass shared UBO and offset, return new offset for next item to be used
682   // don't process bindings if there are no uniform buffers allocated
683   if(uboView)
684   {
685     auto uboCount = reflection.GetUniformBlockCount();
686     mUniformBufferBindings.resize(uboCount);
687
688     std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
689
690     mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
691
692     // Write default uniforms
693     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
694     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
695     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
696     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
697
698     auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
699     if(mvpUniformInfo && !mvpUniformInfo->name.empty())
700     {
701       Matrix modelViewProjectionMatrix(false);
702       Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
703       WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
704     }
705
706     auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
707     if(normalUniformInfo && !normalUniformInfo->name.empty())
708     {
709       Matrix3 normalMatrix(modelViewMatrix);
710       normalMatrix.Invert();
711       normalMatrix.Transpose();
712       WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
713     }
714
715     Vector4        finalColor;                               ///< Applied renderer's opacity color
716     const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
717     if(mPremultipliedAlphaEnabled)
718     {
719       const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
720       finalColor         = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
721     }
722     else
723     {
724       finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
725     }
726     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
727     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
728
729     // Write uniforms from the uniform map
730     FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
731
732     // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
733     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
734
735     commandBuffer.BindUniformBuffers(*bindings);
736   }
737 }
738
739 template<class T>
740 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
741 {
742   if(uniformInfo && !uniformInfo->name.empty())
743   {
744     WriteUniform(ubo, *uniformInfo, data);
745     return true;
746   }
747   return false;
748 }
749
750 template<class T>
751 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
752 {
753   WriteUniform(ubo, uniformInfo, &data, sizeof(T));
754 }
755
756 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
757 {
758   ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
759 }
760
761 void Renderer::FillUniformBuffer(Program&                                      program,
762                                  const SceneGraph::RenderInstruction&          instruction,
763                                  Render::UniformBufferView&                    ubo,
764                                  std::vector<Graphics::UniformBufferBinding>*& outBindings,
765                                  uint32_t&                                     offset,
766                                  BufferIndex                                   updateBufferIndex,
767                                  int                                           nodeIndex)
768 {
769   auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
770   auto  uboCount   = reflection.GetUniformBlockCount();
771
772   // Setup bindings
773   uint32_t dataOffset = offset;
774   for(auto i = 0u; i < uboCount; ++i)
775   {
776     mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
777     mUniformBufferBindings[i].binding  = reflection.GetUniformBlockBinding(i);
778
779     dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
780     mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
781
782     for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
783              end  = mUniformIndexMaps[nodeIndex].end();
784         iter != end;
785         ++iter)
786     {
787       auto& uniform    = *iter;
788       int   arrayIndex = uniform.arrayIndex;
789
790       if(!uniform.uniformFunc)
791       {
792         auto uniformInfo  = Graphics::UniformInfo{};
793         auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
794                                                uniform.uniformNameHash,
795                                                uniform.uniformNameHashNoArray,
796                                                uniformInfo);
797
798         uniform.uniformOffset   = uniformInfo.offset;
799         uniform.uniformLocation = uniformInfo.location;
800
801         if(uniformFound)
802         {
803           auto       dst      = ubo.GetOffset() + uniformInfo.offset;
804           const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
805           const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
806           const auto func     = GetPropertyValueGetter((*iter).propertyValue->GetType());
807
808           ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
809                     typeSize,
810                     dest);
811
812           uniform.uniformSize = typeSize;
813           uniform.uniformFunc = func;
814         }
815       }
816       else
817       {
818         auto       dst      = ubo.GetOffset() + uniform.uniformOffset;
819         const auto typeSize = uniform.uniformSize;
820         const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
821         const auto func     = uniform.uniformFunc;
822
823         ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
824                   typeSize,
825                   dest);
826       }
827     }
828   }
829   // write output bindings
830   outBindings = &mUniformBufferBindings;
831
832   // Update offset
833   offset = dataOffset;
834 }
835
836 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
837 {
838   sortAttributes.shader   = &(mRenderDataProvider->GetShader());
839   sortAttributes.geometry = mGeometry;
840 }
841
842 void Renderer::SetShaderChanged(bool value)
843 {
844   mShaderChanged = value;
845 }
846
847 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
848 {
849   if(mUpdated)
850   {
851     mUpdated = false;
852     return true;
853   }
854
855   if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged())
856   {
857     return true;
858   }
859
860   auto* textures = mRenderDataProvider->GetTextures();
861   if(textures)
862   {
863     for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
864     {
865       auto texture = *iter;
866       if(texture && texture->IsNativeImage())
867       {
868         return true;
869       }
870     }
871   }
872
873   // Hash the property values. If the values are different, then rendering is required.
874   uint64_t                      hash           = 0xc70f6907UL;
875   const SceneGraph::UniformMap& uniformMapNode = node->GetNodeUniformMap();
876   for(uint32_t i = 0u, count = uniformMapNode.Count(); i < count; ++i)
877   {
878     hash = uniformMapNode[i].propertyPtr->Hash(bufferIndex, hash);
879   }
880
881   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
882   const SceneGraph::CollectedUniformMap&    collectedUniformMap    = uniformMapDataProvider.GetCollectedUniformMap();
883   for(uint32_t i = 0u, count = collectedUniformMap.Count(); i < count; ++i)
884   {
885     hash = collectedUniformMap.mUniformMap[i].propertyPtr->Hash(bufferIndex, hash);
886   }
887
888   if(mUniformsHash != hash)
889   {
890     mUniformsHash = hash;
891     return true;
892   }
893
894   return false;
895 }
896
897 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
898   Program&                                             program,
899   const Dali::Internal::SceneGraph::RenderInstruction& instruction,
900   const SceneGraph::NodeDataProvider&                  node,
901   bool                                                 blend)
902 {
903   if(mGeometry->AttributesChanged())
904   {
905     mUpdated = true;
906   }
907
908   // Prepare query info
909   PipelineCacheQueryInfo queryInfo{};
910   queryInfo.program               = &program;
911   queryInfo.renderer              = this;
912   queryInfo.geometry              = mGeometry;
913   queryInfo.blendingEnabled       = blend;
914   queryInfo.blendingOptions       = &mBlendingOptions;
915   queryInfo.alphaPremultiplied    = mPremultipliedAlphaEnabled;
916   queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
917
918   auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
919
920   // should be never null?
921   return *pipelineResult.pipeline;
922 }
923
924 void Renderer::SetRenderCallback(RenderCallback* callback)
925 {
926   mRenderCallback = callback;
927 }
928
929 } // namespace Render
930
931 } // namespace Dali::Internal