2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/render/renderers/render-renderer.h>
22 #include <dali/graphics-api/graphics-program.h>
23 #include <dali/graphics-api/graphics-types.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/common/image-sampler.h>
26 #include <dali/internal/render/common/render-instruction.h>
27 #include <dali/internal/render/data-providers/node-data-provider.h>
28 #include <dali/internal/render/data-providers/uniform-map-data-provider.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/shaders/program.h>
34 #include <dali/internal/render/shaders/scene-graph-shader.h>
35 #include <dali/internal/update/common/uniform-map.h>
43 // Size of uniform buffer page used when resizing
44 constexpr uint32_t UBO_PAGE_SIZE = 8192u;
46 // UBO allocation threshold below which the UBO will shrink
47 constexpr auto UBO_SHRINK_THRESHOLD = 0.75f;
49 // Helper to get the vertex input format
50 Dali::Graphics::VertexInputFormat GetPropertyVertexFormat(Property::Type propertyType)
52 Dali::Graphics::VertexInputFormat type{};
57 case Property::STRING:
60 case Property::EXTENTS: // i4?
61 case Property::RECTANGLE: // i4/f4?
62 case Property::ROTATION:
64 type = Dali::Graphics::VertexInputFormat::UNDEFINED;
67 case Property::BOOLEAN:
69 type = Dali::Graphics::VertexInputFormat::UNDEFINED; // type = GL_BYTE; @todo new type for this?
72 case Property::INTEGER:
74 type = Dali::Graphics::VertexInputFormat::INTEGER; // (short)
79 type = Dali::Graphics::VertexInputFormat::FLOAT;
82 case Property::VECTOR2:
84 type = Dali::Graphics::VertexInputFormat::FVECTOR2;
87 case Property::VECTOR3:
89 type = Dali::Graphics::VertexInputFormat::FVECTOR3;
92 case Property::VECTOR4:
94 type = Dali::Graphics::VertexInputFormat::FVECTOR4;
97 case Property::MATRIX3:
99 type = Dali::Graphics::VertexInputFormat::FLOAT;
102 case Property::MATRIX:
104 type = Dali::Graphics::VertexInputFormat::FLOAT;
112 constexpr Graphics::CullMode ConvertCullFace(Dali::FaceCullingMode::Type mode)
116 case Dali::FaceCullingMode::NONE:
118 return Graphics::CullMode::NONE;
120 case Dali::FaceCullingMode::FRONT:
122 return Graphics::CullMode::FRONT;
124 case Dali::FaceCullingMode::BACK:
126 return Graphics::CullMode::BACK;
128 case Dali::FaceCullingMode::FRONT_AND_BACK:
130 return Graphics::CullMode::FRONT_AND_BACK;
133 return Graphics::CullMode::NONE;
136 constexpr Graphics::BlendFactor ConvertBlendFactor(BlendFactor::Type blendFactor)
140 case BlendFactor::ZERO:
141 return Graphics::BlendFactor::ZERO;
142 case BlendFactor::ONE:
143 return Graphics::BlendFactor::ONE;
144 case BlendFactor::SRC_COLOR:
145 return Graphics::BlendFactor::SRC_COLOR;
146 case BlendFactor::ONE_MINUS_SRC_COLOR:
147 return Graphics::BlendFactor::ONE_MINUS_SRC_COLOR;
148 case BlendFactor::SRC_ALPHA:
149 return Graphics::BlendFactor::SRC_ALPHA;
150 case BlendFactor::ONE_MINUS_SRC_ALPHA:
151 return Graphics::BlendFactor::ONE_MINUS_SRC_ALPHA;
152 case BlendFactor::DST_ALPHA:
153 return Graphics::BlendFactor::DST_ALPHA;
154 case BlendFactor::ONE_MINUS_DST_ALPHA:
155 return Graphics::BlendFactor::ONE_MINUS_DST_ALPHA;
156 case BlendFactor::DST_COLOR:
157 return Graphics::BlendFactor::DST_COLOR;
158 case BlendFactor::ONE_MINUS_DST_COLOR:
159 return Graphics::BlendFactor::ONE_MINUS_DST_COLOR;
160 case BlendFactor::SRC_ALPHA_SATURATE:
161 return Graphics::BlendFactor::SRC_ALPHA_SATURATE;
162 case BlendFactor::CONSTANT_COLOR:
163 return Graphics::BlendFactor::CONSTANT_COLOR;
164 case BlendFactor::ONE_MINUS_CONSTANT_COLOR:
165 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_COLOR;
166 case BlendFactor::CONSTANT_ALPHA:
167 return Graphics::BlendFactor::CONSTANT_ALPHA;
168 case BlendFactor::ONE_MINUS_CONSTANT_ALPHA:
169 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_ALPHA;
171 return Graphics::BlendFactor{};
174 constexpr Graphics::BlendOp ConvertBlendEquation(DevelBlendEquation::Type blendEquation)
176 switch(blendEquation)
178 case DevelBlendEquation::ADD:
179 return Graphics::BlendOp::ADD;
180 case DevelBlendEquation::SUBTRACT:
181 return Graphics::BlendOp::SUBTRACT;
182 case DevelBlendEquation::REVERSE_SUBTRACT:
183 return Graphics::BlendOp::REVERSE_SUBTRACT;
184 case DevelBlendEquation::COLOR:
185 case DevelBlendEquation::COLOR_BURN:
186 case DevelBlendEquation::COLOR_DODGE:
187 case DevelBlendEquation::DARKEN:
188 case DevelBlendEquation::DIFFERENCE:
189 case DevelBlendEquation::EXCLUSION:
190 case DevelBlendEquation::HARD_LIGHT:
191 case DevelBlendEquation::HUE:
192 case DevelBlendEquation::LIGHTEN:
193 case DevelBlendEquation::LUMINOSITY:
194 case DevelBlendEquation::MAX:
195 case DevelBlendEquation::MIN:
196 case DevelBlendEquation::MULTIPLY:
197 case DevelBlendEquation::OVERLAY:
198 case DevelBlendEquation::SATURATION:
199 case DevelBlendEquation::SCREEN:
200 case DevelBlendEquation::SOFT_LIGHT:
201 return Graphics::BlendOp{};
203 return Graphics::BlendOp{};
207 * Helper function to calculate the correct alignment of data for uniform buffers
208 * @param dataSize size of uniform buffer
209 * @return aligned offset of data
211 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
213 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
220 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
221 Render::Geometry* geometry,
222 uint32_t blendingBitmask,
223 const Vector4& blendColor,
224 FaceCullingMode::Type faceCullingMode,
225 bool preMultipliedAlphaEnabled,
226 DepthWriteMode::Type depthWriteMode,
227 DepthTestMode::Type depthTestMode,
228 DepthFunction::Type depthFunction,
229 StencilParameters& stencilParameters)
231 return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
234 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
235 Render::Geometry* geometry,
236 uint32_t blendingBitmask,
237 const Vector4& blendColor,
238 FaceCullingMode::Type faceCullingMode,
239 bool preMultipliedAlphaEnabled,
240 DepthWriteMode::Type depthWriteMode,
241 DepthTestMode::Type depthTestMode,
242 DepthFunction::Type depthFunction,
243 StencilParameters& stencilParameters)
244 : mGraphicsController(nullptr),
245 mRenderDataProvider(dataProvider),
248 mProgramCache(nullptr),
250 mAttributeLocations(),
252 mStencilParameters(stencilParameters),
254 mIndexedDrawFirstElement(0),
255 mIndexedDrawElementsCount(0),
256 mDepthFunction(depthFunction),
257 mFaceCullingMode(faceCullingMode),
258 mDepthWriteMode(depthWriteMode),
259 mDepthTestMode(depthTestMode),
260 mUpdateAttributeLocations(true),
261 mPremultipledAlphaEnabled(preMultipliedAlphaEnabled),
262 mShaderChanged(false),
265 if(blendingBitmask != 0u)
267 mBlendingOptions.SetBitmask(blendingBitmask);
270 mBlendingOptions.SetBlendColor(blendColor);
273 void Renderer::Initialize(Context& context, Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager)
276 mGraphicsController = &graphicsController;
277 mProgramCache = &programCache;
278 mShaderCache = &shaderCache;
279 mUniformBufferManager = &uniformBufferManager;
282 Renderer::~Renderer() = default;
284 void Renderer::SetGeometry(Render::Geometry* geometry)
286 mGeometry = geometry;
287 mUpdateAttributeLocations = true;
289 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
291 mDrawCommands.clear();
292 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
295 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
297 uint32_t textureUnit = 0;
299 std::vector<Render::Sampler*>& samplers(mRenderDataProvider->GetSamplers());
300 std::vector<Render::Texture*>& textures(mRenderDataProvider->GetTextures());
302 std::vector<Graphics::TextureBinding> textureBindings;
303 for(uint32_t i = 0; i < static_cast<uint32_t>(textures.size()); ++i) // not expecting more than uint32_t of textures
305 if(textures[i] && textures[i]->GetGraphicsObject())
307 // if the sampler exists,
308 // if it's default, delete the graphics object
309 // otherwise re-initialize it if dirty
311 const Graphics::Sampler* graphicsSampler = (samplers[i] ? samplers[i]->GetGraphicsObject()
314 boundTextures.PushBack(textures[i]->GetGraphicsObject());
315 const Graphics::TextureBinding textureBinding{textures[i]->GetGraphicsObject(), graphicsSampler, textureUnit};
316 textureBindings.push_back(textureBinding);
322 if(textureBindings.size() > 0)
324 commandBuffer.BindTextures(textureBindings);
328 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
330 mFaceCullingMode = mode;
334 void Renderer::SetBlendingBitMask(uint32_t bitmask)
336 mBlendingOptions.SetBitmask(bitmask);
340 void Renderer::SetBlendColor(const Vector4& color)
342 mBlendingOptions.SetBlendColor(color);
346 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
348 mIndexedDrawFirstElement = firstElement;
352 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
354 mIndexedDrawElementsCount = elementsCount;
358 void Renderer::EnablePreMultipliedAlpha(bool enable)
360 mPremultipledAlphaEnabled = enable;
364 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
366 mDepthWriteMode = depthWriteMode;
370 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
372 mDepthTestMode = depthTestMode;
376 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
378 return mDepthWriteMode;
381 DepthTestMode::Type Renderer::GetDepthTestMode() const
383 return mDepthTestMode;
386 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
388 mDepthFunction = depthFunction;
392 DepthFunction::Type Renderer::GetDepthFunction() const
394 return mDepthFunction;
397 void Renderer::SetRenderMode(RenderMode::Type renderMode)
399 mStencilParameters.renderMode = renderMode;
403 RenderMode::Type Renderer::GetRenderMode() const
405 return mStencilParameters.renderMode;
408 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
410 mStencilParameters.stencilFunction = stencilFunction;
414 StencilFunction::Type Renderer::GetStencilFunction() const
416 return mStencilParameters.stencilFunction;
419 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
421 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
425 int Renderer::GetStencilFunctionMask() const
427 return mStencilParameters.stencilFunctionMask;
430 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
432 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
436 int Renderer::GetStencilFunctionReference() const
438 return mStencilParameters.stencilFunctionReference;
441 void Renderer::SetStencilMask(int stencilMask)
443 mStencilParameters.stencilMask = stencilMask;
447 int Renderer::GetStencilMask() const
449 return mStencilParameters.stencilMask;
452 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
454 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
458 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
460 return mStencilParameters.stencilOperationOnFail;
463 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
465 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
469 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
471 return mStencilParameters.stencilOperationOnZFail;
474 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
476 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
480 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
482 return mStencilParameters.stencilOperationOnZPass;
485 void Renderer::Upload()
487 mGeometry->Upload(*mGraphicsController);
490 bool Renderer::Render(Graphics::CommandBuffer& commandBuffer,
491 BufferIndex bufferIndex,
492 const SceneGraph::NodeDataProvider& node,
493 const Matrix& modelMatrix,
494 const Matrix& modelViewMatrix,
495 const Matrix& viewMatrix,
496 const Matrix& projectionMatrix,
499 Vector<Graphics::Texture*>& boundTextures,
500 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
503 // Before doing anything test if the call happens in the right queue
504 if(mDrawCommands.empty() && queueIndex > 0)
510 std::vector<DevelRenderer::DrawCommand*> commands;
511 for(auto& cmd : mDrawCommands)
513 if(cmd.queue == queueIndex)
515 commands.emplace_back(&cmd);
519 // Have commands but nothing to be drawn - abort
520 if(!mDrawCommands.empty() && commands.empty())
526 if(!mDrawCommands.empty())
528 blend = (commands[0]->queue == DevelRenderer::RENDER_QUEUE_OPAQUE ? false : blend);
532 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
533 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
534 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
535 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
537 Graphics::PipelineStage::VERTEX_SHADER,
538 shaderData->GetSourceMode());
540 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
542 Graphics::PipelineStage::FRAGMENT_SHADER,
543 shaderData->GetSourceMode());
545 std::vector<Graphics::ShaderState> shaderStates{
546 Graphics::ShaderState()
547 .SetShader(vertexShader)
548 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
549 Graphics::ShaderState()
550 .SetShader(fragmentShader)
551 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
553 auto createInfo = Graphics::ProgramCreateInfo();
554 createInfo.SetShaderState(shaderStates);
556 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
557 Program* program = Program::New(*mProgramCache,
559 *mGraphicsController,
560 std::move(graphicsProgram),
561 (shaderData->GetHints() & Dali::Shader::Hint::MODIFIES_GEOMETRY) != 0x0);
565 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<void*>(&mRenderDataProvider->GetShader()));
569 // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
570 auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
572 commandBuffer.BindPipeline(pipeline);
574 BindTextures(commandBuffer, boundTextures);
576 BuildUniformIndexMap(bufferIndex, node, size, *program);
578 WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
580 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
581 // @todo We should detect this case much earlier to prevent unnecessary work
583 if(mDrawCommands.empty())
585 drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
589 for(auto& cmd : commands)
591 mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
599 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
601 // Check if the map has changed
602 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
604 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
606 if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
607 node.GetUniformMapChanged(bufferIndex) ||
608 mUniformIndexMap.Count() == 0 ||
611 // Reset shader pointer
612 mShaderChanged = false;
614 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
615 const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
617 uint32_t maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
618 mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
619 mUniformIndexMap.Resize(maxMaps);
621 uint32_t mapIndex = 0;
622 for(; mapIndex < uniformMap.Count(); ++mapIndex)
624 mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex].propertyPtr;
625 mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform(uniformMap[mapIndex].uniformName);
626 mUniformIndexMap[mapIndex].uniformName = uniformMap[mapIndex].uniformName;
627 mUniformIndexMap[mapIndex].uniformNameHash = uniformMap[mapIndex].uniformNameHash;
628 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
629 mUniformIndexMap[mapIndex].arrayIndex = uniformMap[mapIndex].arrayIndex;
632 for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
634 uint32_t uniformIndex = program.RegisterUniform(uniformMapNode[nodeMapIndex].uniformName);
636 for(uint32_t i = 0; i < uniformMap.Count(); ++i)
638 if(mUniformIndexMap[i].uniformIndex == uniformIndex)
640 mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
648 mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
649 mUniformIndexMap[mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
650 mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
651 mUniformIndexMap[mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
652 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
653 mUniformIndexMap[mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
658 mUniformIndexMap.Resize(mapIndex);
662 void Renderer::WriteUniformBuffer(
663 BufferIndex bufferIndex,
664 Graphics::CommandBuffer& commandBuffer,
666 const SceneGraph::RenderInstruction& instruction,
667 const SceneGraph::NodeDataProvider& node,
668 const Matrix& modelMatrix,
669 const Matrix& modelViewMatrix,
670 const Matrix& viewMatrix,
671 const Matrix& projectionMatrix,
675 uint32_t uniformBlockAllocationBytes{0u};
676 uint32_t uniformBlockMaxSize{0u};
677 uint32_t uboOffset{0u};
679 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
680 for(auto i = 0u; i < reflection.GetUniformBlockCount(); ++i)
682 auto blockSize = GetUniformBufferDataAlignment(reflection.GetUniformBlockSize(i));
683 if(uniformBlockMaxSize < blockSize)
685 uniformBlockMaxSize = blockSize;
687 uniformBlockAllocationBytes += blockSize;
690 auto pagedAllocation = ((uniformBlockAllocationBytes / UBO_PAGE_SIZE + 1u)) * UBO_PAGE_SIZE;
692 // Allocate twice memory as required by the uniform buffers
693 // todo: memory usage backlog to use optimal allocation
694 if(uniformBlockAllocationBytes && !mUniformBuffer[bufferIndex])
696 mUniformBuffer[bufferIndex] = mUniformBufferManager->AllocateUniformBuffer(pagedAllocation);
698 else if(uniformBlockAllocationBytes && (mUniformBuffer[bufferIndex]->GetSize() < pagedAllocation ||
699 (pagedAllocation < uint32_t(float(mUniformBuffer[bufferIndex]->GetSize()) * UBO_SHRINK_THRESHOLD))))
701 mUniformBuffer[bufferIndex]->Reserve(pagedAllocation);
705 if(mUniformBuffer[bufferIndex])
707 mUniformBuffer[bufferIndex]->Fill(0, 0u, 0u);
710 // update the uniform buffer
711 // pass shared UBO and offset, return new offset for next item to be used
712 // don't process bindings if there are no uniform buffers allocated
713 auto ubo = mUniformBuffer[bufferIndex].get();
716 auto uboCount = reflection.GetUniformBlockCount();
717 mUniformBufferBindings.resize(uboCount);
719 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
721 // Write default uniforms
722 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *ubo, *bindings, modelMatrix);
723 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *ubo, *bindings, viewMatrix);
724 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *ubo, *bindings, projectionMatrix);
725 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *ubo, *bindings, modelViewMatrix);
727 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
728 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
730 Matrix modelViewProjectionMatrix(false);
731 Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
732 WriteDefaultUniform(mvpUniformInfo, *ubo, *bindings, modelViewProjectionMatrix);
735 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
736 if(normalUniformInfo && !normalUniformInfo->name.empty())
738 Matrix3 normalMatrix(modelViewMatrix);
739 normalMatrix.Invert();
740 normalMatrix.Transpose();
741 WriteDefaultUniform(normalUniformInfo, *ubo, *bindings, normalMatrix);
745 const Vector4& color = node.GetRenderColor(bufferIndex);
746 if(mPremultipledAlphaEnabled)
748 float alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
749 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
753 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
755 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *ubo, *bindings, finalColor);
757 // Write uniforms from the uniform map
758 FillUniformBuffer(*program, instruction, *ubo, bindings, uboOffset, bufferIndex);
760 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
761 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *ubo, *bindings, size);
763 commandBuffer.BindUniformBuffers(*bindings);
768 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data)
770 if(uniformInfo && !uniformInfo->name.empty())
772 WriteUniform(ubo, bindings, *uniformInfo, data);
779 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data)
781 WriteUniform(ubo, bindings, uniformInfo, &data, sizeof(T));
784 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
786 ubo.Write(data, size, bindings[uniformInfo.bufferIndex].offset + uniformInfo.offset);
789 void Renderer::FillUniformBuffer(Program& program,
790 const SceneGraph::RenderInstruction& instruction,
791 Render::UniformBuffer& ubo,
792 std::vector<Graphics::UniformBufferBinding>*& outBindings,
794 BufferIndex updateBufferIndex)
796 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
797 auto uboCount = reflection.GetUniformBlockCount();
800 uint32_t dataOffset = offset;
801 for(auto i = 0u; i < uboCount; ++i)
803 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
804 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
805 mUniformBufferBindings[i].offset = dataOffset;
807 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
808 mUniformBufferBindings[i].buffer = ubo.GetBuffer();
810 for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
811 end = mUniformIndexMap.End();
815 // @todo This means parsing the uniform string every frame. Instead, store the array index if present.
816 int arrayIndex = (*iter).arrayIndex;
818 auto uniformInfo = Graphics::UniformInfo{};
819 auto uniformFound = program.GetUniform((*iter).uniformName.GetCString(),
820 (*iter).uniformNameHashNoArray ? (*iter).uniformNameHashNoArray
821 : (*iter).uniformNameHash,
826 auto dst = mUniformBufferBindings[uniformInfo.bufferIndex].offset + uniformInfo.offset;
828 switch((*iter).propertyValue->GetType())
830 case Property::Type::BOOLEAN:
832 ubo.Write(&(*iter).propertyValue->GetBoolean(updateBufferIndex),
834 dst + static_cast<uint32_t>(sizeof(bool)) * arrayIndex);
837 case Property::Type::INTEGER:
839 ubo.Write(&(*iter).propertyValue->GetInteger(updateBufferIndex),
841 dst + static_cast<int32_t>(sizeof(int32_t)) * arrayIndex);
844 case Property::Type::FLOAT:
846 ubo.Write(&(*iter).propertyValue->GetFloat(updateBufferIndex),
848 dst + static_cast<uint32_t>(sizeof(float)) * arrayIndex);
851 case Property::Type::VECTOR2:
853 ubo.Write(&(*iter).propertyValue->GetVector2(updateBufferIndex),
855 dst + static_cast<uint32_t>(sizeof(Vector2)) * arrayIndex);
858 case Property::Type::VECTOR3:
860 ubo.Write(&(*iter).propertyValue->GetVector3(updateBufferIndex),
862 dst + static_cast<uint32_t>(sizeof(Vector3)) * arrayIndex);
865 case Property::Type::VECTOR4:
867 ubo.Write(&(*iter).propertyValue->GetVector4(updateBufferIndex),
869 dst + static_cast<uint32_t>(sizeof(Vector4)) * arrayIndex);
872 case Property::Type::MATRIX:
874 ubo.Write(&(*iter).propertyValue->GetMatrix(updateBufferIndex),
876 dst + static_cast<uint32_t>(sizeof(Matrix)) * arrayIndex);
879 case Property::Type::MATRIX3:
881 // todo: handle data padding properly
884 //const auto& matrix = &(*iter).propertyValue->GetMatrix3(updateBufferIndex);
885 //for(int i = 0; i < 3; ++i)
887 //ubo.Write(&matrix->AsFloat()[i * 3],
888 // sizeof(float) * 3,
889 // dst + (i * static_cast<uint32_t>(sizeof(Vector4))));
892 ubo.Write(&(*iter).propertyValue->GetMatrix3(updateBufferIndex),
894 dst + static_cast<uint32_t>(sizeof(Matrix3)) * arrayIndex);
904 // write output bindings
905 outBindings = &mUniformBufferBindings;
911 void Renderer::SetSortAttributes(BufferIndex bufferIndex,
912 SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
914 sortAttributes.shader = &(mRenderDataProvider->GetShader());
915 sortAttributes.geometry = mGeometry;
918 void Renderer::SetShaderChanged(bool value)
920 mShaderChanged = value;
923 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
931 if(mShaderChanged || mUpdateAttributeLocations || mGeometry->AttributesChanged())
936 for(const auto& texture : mRenderDataProvider->GetTextures())
938 if(texture && texture->IsNativeImage())
944 uint64_t hash = 0xc70f6907UL;
945 const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
946 for(const auto& uniformProperty : uniformMapNode)
948 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
951 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
952 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
953 for(const auto& uniformProperty : uniformMap)
955 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
958 if(mUniformsHash != hash)
960 mUniformsHash = hash;
967 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
969 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
970 const SceneGraph::NodeDataProvider& node,
973 Graphics::InputAssemblyState inputAssemblyState{};
974 Graphics::VertexInputState vertexInputState{};
975 Graphics::ProgramState programState{};
976 uint32_t bindingIndex{0u};
978 if(mUpdateAttributeLocations || mGeometry->AttributesChanged())
980 mAttributeLocations.Clear();
981 mUpdateAttributeLocations = true;
984 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
990 for(auto&& vertexBuffer : mGeometry->GetVertexBuffers())
992 const VertexBuffer::Format& vertexFormat = *vertexBuffer->GetFormat();
994 vertexInputState.bufferBindings.emplace_back(vertexFormat.size, // stride
995 Graphics::VertexInputRate::PER_VERTEX);
997 const uint32_t attributeCount = vertexBuffer->GetAttributeCount();
998 for(uint32_t i = 0; i < attributeCount; ++i)
1000 if(mUpdateAttributeLocations)
1002 auto attributeName = vertexBuffer->GetAttributeName(i);
1003 int32_t pLocation = reflection.GetVertexAttributeLocation(std::string(attributeName.GetStringView()));
1006 DALI_LOG_WARNING("Attribute not found in the shader: %s\n", attributeName.GetCString());
1008 mAttributeLocations.PushBack(pLocation);
1011 uint32_t location = static_cast<uint32_t>(mAttributeLocations[base + i]);
1013 vertexInputState.attributes.emplace_back(location,
1015 vertexFormat.components[i].offset,
1016 GetPropertyVertexFormat(vertexFormat.components[i].type));
1018 base += attributeCount;
1021 mUpdateAttributeLocations = false;
1024 inputAssemblyState.SetTopology(mGeometry->GetTopology());
1027 programState.SetProgram(program.GetGraphicsProgram());
1029 Graphics::RasterizationState rasterizationState{};
1031 //Set cull face mode
1032 const Dali::Internal::SceneGraph::Camera* cam = instruction.GetCamera();
1033 if(cam->GetReflectionUsed())
1035 auto adjFaceCullingMode = mFaceCullingMode;
1036 switch(mFaceCullingMode)
1038 case FaceCullingMode::Type::FRONT:
1040 adjFaceCullingMode = FaceCullingMode::Type::BACK;
1043 case FaceCullingMode::Type::BACK:
1045 adjFaceCullingMode = FaceCullingMode::Type::FRONT;
1050 // nothing to do, leave culling as it is
1053 rasterizationState.SetCullMode(ConvertCullFace(adjFaceCullingMode));
1057 rasterizationState.SetCullMode(ConvertCullFace(mFaceCullingMode));
1060 rasterizationState.SetFrontFace(Graphics::FrontFace::COUNTER_CLOCKWISE);
1065 switch(mGeometry->GetTopology())
1067 case Graphics::PrimitiveTopology::TRIANGLE_LIST:
1068 case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
1069 case Graphics::PrimitiveTopology::TRIANGLE_FAN:
1070 rasterizationState.SetPolygonMode(Graphics::PolygonMode::FILL);
1072 case Graphics::PrimitiveTopology::LINE_LIST:
1073 case Graphics::PrimitiveTopology::LINE_LOOP:
1074 case Graphics::PrimitiveTopology::LINE_STRIP:
1075 rasterizationState.SetPolygonMode(Graphics::PolygonMode::LINE);
1077 case Graphics::PrimitiveTopology::POINT_LIST:
1078 rasterizationState.SetPolygonMode(Graphics::PolygonMode::POINT);
1082 // @todo How to signal a blend barrier is needed?
1083 //if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1085 // context.BlendBarrier();
1088 Graphics::ColorBlendState colorBlendState{};
1089 colorBlendState.SetBlendEnable(false);
1093 colorBlendState.SetBlendEnable(true);
1095 Graphics::BlendOp rgbOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1096 Graphics::BlendOp alphaOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1097 if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1099 if(rgbOp != alphaOp)
1101 DALI_LOG_ERROR("Advanced Blend Equation MUST be applied by using BlendEquation.\n");
1107 .SetSrcColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorRgb()))
1108 .SetSrcAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorAlpha()))
1109 .SetDstColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorRgb()))
1110 .SetDstAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorAlpha()))
1111 .SetColorBlendOp(rgbOp)
1112 .SetAlphaBlendOp(alphaOp);
1114 // Blend color is optional and rarely used
1115 Vector4* blendColor = const_cast<Vector4*>(mBlendingOptions.GetBlendColor());
1118 colorBlendState.SetBlendConstants(blendColor->AsFloat());
1124 // Create the pipeline
1125 Graphics::PipelineCreateInfo createInfo;
1127 .SetInputAssemblyState(&inputAssemblyState)
1128 .SetVertexInputState(&vertexInputState)
1129 .SetRasterizationState(&rasterizationState)
1130 .SetColorBlendState(&colorBlendState)
1131 .SetProgramState(&programState)
1132 .SetNextExtension(&mLegacyProgram);
1134 // Store a pipeline per renderer per render (renderer can be owned by multiple nodes,
1135 // and re-drawn in multiple instructions).
1136 // @todo This is only needed because ColorBlend state can change. Fixme!
1137 // This is ameliorated by the fact that implementation caches pipelines, and we're only storing
1139 auto hash = HashedPipeline::GetHash(&node, &instruction, blend);
1140 HashedPipeline* hashedPipeline = nullptr;
1141 for(auto& element : mGraphicsPipelines)
1143 if(element.mHash == hash)
1145 hashedPipeline = &element;
1150 if(hashedPipeline != nullptr)
1152 hashedPipeline->mGraphicsPipeline = mGraphicsController->CreatePipeline(
1154 std::move(hashedPipeline->mGraphicsPipeline));
1158 mGraphicsPipelines.emplace_back();
1159 mGraphicsPipelines.back().mHash = hash;
1160 mGraphicsPipelines.back().mGraphicsPipeline = mGraphicsController->CreatePipeline(createInfo, nullptr);
1161 hashedPipeline = &mGraphicsPipelines.back();
1163 return *hashedPipeline->mGraphicsPipeline.get();
1166 } // namespace Render
1168 } // namespace Internal