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/gl-resources/context.h>
30 #include <dali/internal/render/renderers/render-sampler.h>
31 #include <dali/internal/render/renderers/render-texture.h>
32 #include <dali/internal/render/renderers/render-vertex-buffer.h>
33 #include <dali/internal/render/renderers/shader-cache.h>
34 #include <dali/internal/render/shaders/program.h>
35 #include <dali/internal/render/shaders/scene-graph-shader.h>
36 #include <dali/internal/update/common/uniform-map.h>
44 // Size of uniform buffer page used when resizing
45 constexpr uint32_t UBO_PAGE_SIZE = 8192u;
47 // UBO allocation threshold below which the UBO will shrink
48 constexpr auto UBO_SHRINK_THRESHOLD = 0.75f;
50 // Helper to get the vertex input format
51 Dali::Graphics::VertexInputFormat GetPropertyVertexFormat(Property::Type propertyType)
53 Dali::Graphics::VertexInputFormat type{};
58 case Property::STRING:
61 case Property::EXTENTS: // i4?
62 case Property::RECTANGLE: // i4/f4?
63 case Property::ROTATION:
65 type = Dali::Graphics::VertexInputFormat::UNDEFINED;
68 case Property::BOOLEAN:
70 type = Dali::Graphics::VertexInputFormat::UNDEFINED; // type = GL_BYTE; @todo new type for this?
73 case Property::INTEGER:
75 type = Dali::Graphics::VertexInputFormat::INTEGER; // (short)
80 type = Dali::Graphics::VertexInputFormat::FLOAT;
83 case Property::VECTOR2:
85 type = Dali::Graphics::VertexInputFormat::FVECTOR2;
88 case Property::VECTOR3:
90 type = Dali::Graphics::VertexInputFormat::FVECTOR3;
93 case Property::VECTOR4:
95 type = Dali::Graphics::VertexInputFormat::FVECTOR4;
98 case Property::MATRIX3:
100 type = Dali::Graphics::VertexInputFormat::FLOAT;
103 case Property::MATRIX:
105 type = Dali::Graphics::VertexInputFormat::FLOAT;
113 constexpr Graphics::CullMode ConvertCullFace(Dali::FaceCullingMode::Type mode)
117 case Dali::FaceCullingMode::NONE:
119 return Graphics::CullMode::NONE;
121 case Dali::FaceCullingMode::FRONT:
123 return Graphics::CullMode::FRONT;
125 case Dali::FaceCullingMode::BACK:
127 return Graphics::CullMode::BACK;
129 case Dali::FaceCullingMode::FRONT_AND_BACK:
131 return Graphics::CullMode::FRONT_AND_BACK;
134 return Graphics::CullMode::NONE;
137 constexpr Graphics::BlendFactor ConvertBlendFactor(BlendFactor::Type blendFactor)
141 case BlendFactor::ZERO:
142 return Graphics::BlendFactor::ZERO;
143 case BlendFactor::ONE:
144 return Graphics::BlendFactor::ONE;
145 case BlendFactor::SRC_COLOR:
146 return Graphics::BlendFactor::SRC_COLOR;
147 case BlendFactor::ONE_MINUS_SRC_COLOR:
148 return Graphics::BlendFactor::ONE_MINUS_SRC_COLOR;
149 case BlendFactor::SRC_ALPHA:
150 return Graphics::BlendFactor::SRC_ALPHA;
151 case BlendFactor::ONE_MINUS_SRC_ALPHA:
152 return Graphics::BlendFactor::ONE_MINUS_SRC_ALPHA;
153 case BlendFactor::DST_ALPHA:
154 return Graphics::BlendFactor::DST_ALPHA;
155 case BlendFactor::ONE_MINUS_DST_ALPHA:
156 return Graphics::BlendFactor::ONE_MINUS_DST_ALPHA;
157 case BlendFactor::DST_COLOR:
158 return Graphics::BlendFactor::DST_COLOR;
159 case BlendFactor::ONE_MINUS_DST_COLOR:
160 return Graphics::BlendFactor::ONE_MINUS_DST_COLOR;
161 case BlendFactor::SRC_ALPHA_SATURATE:
162 return Graphics::BlendFactor::SRC_ALPHA_SATURATE;
163 case BlendFactor::CONSTANT_COLOR:
164 return Graphics::BlendFactor::CONSTANT_COLOR;
165 case BlendFactor::ONE_MINUS_CONSTANT_COLOR:
166 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_COLOR;
167 case BlendFactor::CONSTANT_ALPHA:
168 return Graphics::BlendFactor::CONSTANT_ALPHA;
169 case BlendFactor::ONE_MINUS_CONSTANT_ALPHA:
170 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_ALPHA;
172 return Graphics::BlendFactor{};
175 constexpr Graphics::BlendOp ConvertBlendEquation(DevelBlendEquation::Type blendEquation)
177 switch(blendEquation)
179 case DevelBlendEquation::ADD:
180 return Graphics::BlendOp::ADD;
181 case DevelBlendEquation::SUBTRACT:
182 return Graphics::BlendOp::SUBTRACT;
183 case DevelBlendEquation::REVERSE_SUBTRACT:
184 return Graphics::BlendOp::REVERSE_SUBTRACT;
185 case DevelBlendEquation::COLOR:
186 case DevelBlendEquation::COLOR_BURN:
187 case DevelBlendEquation::COLOR_DODGE:
188 case DevelBlendEquation::DARKEN:
189 case DevelBlendEquation::DIFFERENCE:
190 case DevelBlendEquation::EXCLUSION:
191 case DevelBlendEquation::HARD_LIGHT:
192 case DevelBlendEquation::HUE:
193 case DevelBlendEquation::LIGHTEN:
194 case DevelBlendEquation::LUMINOSITY:
195 case DevelBlendEquation::MAX:
196 case DevelBlendEquation::MIN:
197 case DevelBlendEquation::MULTIPLY:
198 case DevelBlendEquation::OVERLAY:
199 case DevelBlendEquation::SATURATION:
200 case DevelBlendEquation::SCREEN:
201 case DevelBlendEquation::SOFT_LIGHT:
202 return Graphics::BlendOp{};
204 return Graphics::BlendOp{};
208 * Helper function to calculate the correct alignment of data for uniform buffers
209 * @param dataSize size of uniform buffer
210 * @return aligned offset of data
212 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
214 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
221 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
222 Render::Geometry* geometry,
223 uint32_t blendingBitmask,
224 const Vector4& blendColor,
225 FaceCullingMode::Type faceCullingMode,
226 bool preMultipliedAlphaEnabled,
227 DepthWriteMode::Type depthWriteMode,
228 DepthTestMode::Type depthTestMode,
229 DepthFunction::Type depthFunction,
230 StencilParameters& stencilParameters)
232 return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
235 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
236 Render::Geometry* geometry,
237 uint32_t blendingBitmask,
238 const Vector4& blendColor,
239 FaceCullingMode::Type faceCullingMode,
240 bool preMultipliedAlphaEnabled,
241 DepthWriteMode::Type depthWriteMode,
242 DepthTestMode::Type depthTestMode,
243 DepthFunction::Type depthFunction,
244 StencilParameters& stencilParameters)
245 : mGraphicsController(nullptr),
246 mRenderDataProvider(dataProvider),
249 mProgramCache(nullptr),
251 mAttributeLocations(),
253 mStencilParameters(stencilParameters),
255 mIndexedDrawFirstElement(0),
256 mIndexedDrawElementsCount(0),
257 mDepthFunction(depthFunction),
258 mFaceCullingMode(faceCullingMode),
259 mDepthWriteMode(depthWriteMode),
260 mDepthTestMode(depthTestMode),
261 mUpdateAttributeLocations(true),
262 mPremultipledAlphaEnabled(preMultipliedAlphaEnabled),
263 mShaderChanged(false),
266 if(blendingBitmask != 0u)
268 mBlendingOptions.SetBitmask(blendingBitmask);
271 mBlendingOptions.SetBlendColor(blendColor);
274 void Renderer::Initialize(Context& context, Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager)
277 mGraphicsController = &graphicsController;
278 mProgramCache = &programCache;
279 mShaderCache = &shaderCache;
280 mUniformBufferManager = &uniformBufferManager;
283 Renderer::~Renderer() = default;
285 void Renderer::SetGeometry(Render::Geometry* geometry)
287 mGeometry = geometry;
288 mUpdateAttributeLocations = true;
290 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
292 mDrawCommands.clear();
293 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
296 void Renderer::SetUniformFromProperty(BufferIndex bufferIndex, Program& program, UniformIndexMap& map)
298 GLint location = program.GetUniformLocation(map.uniformIndex);
299 if(Program::UNIFORM_UNKNOWN != location)
301 // switch based on property type to use correct GL uniform setter
302 switch(map.propertyValue->GetType())
304 case Property::INTEGER:
306 program.SetUniform1i(location, map.propertyValue->GetInteger(bufferIndex));
309 case Property::FLOAT:
311 program.SetUniform1f(location, map.propertyValue->GetFloat(bufferIndex));
314 case Property::VECTOR2:
316 Vector2 value(map.propertyValue->GetVector2(bufferIndex));
317 program.SetUniform2f(location, value.x, value.y);
321 case Property::VECTOR3:
323 Vector3 value(map.propertyValue->GetVector3(bufferIndex));
324 program.SetUniform3f(location, value.x, value.y, value.z);
328 case Property::VECTOR4:
330 Vector4 value(map.propertyValue->GetVector4(bufferIndex));
331 program.SetUniform4f(location, value.x, value.y, value.z, value.w);
335 case Property::ROTATION:
337 Quaternion value(map.propertyValue->GetQuaternion(bufferIndex));
338 program.SetUniform4f(location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w);
342 case Property::MATRIX:
344 const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
345 program.SetUniformMatrix4fv(location, 1, value.AsFloat());
349 case Property::MATRIX3:
351 const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
352 program.SetUniformMatrix3fv(location, 1, value.AsFloat());
358 // Other property types are ignored
365 void Renderer::BindTextures(Program& program, Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
367 uint32_t textureUnit = 0;
369 GLint uniformLocation(-1);
370 std::vector<Render::Sampler*>& samplers(mRenderDataProvider->GetSamplers());
371 std::vector<Render::Texture*>& textures(mRenderDataProvider->GetTextures());
373 std::vector<Graphics::TextureBinding> textureBindings;
374 for(uint32_t i = 0; i < static_cast<uint32_t>(textures.size()); ++i) // not expecting more than uint32_t of textures
376 if(textures[i] && textures[i]->GetGraphicsObject())
378 if(program.GetSamplerUniformLocation(i, uniformLocation))
380 // if the sampler exists,
381 // if it's default, delete the graphics object
382 // otherwise re-initialize it if dirty
384 const Graphics::Sampler* graphicsSampler = (samplers[i] ? samplers[i]->GetGraphicsObject()
387 boundTextures.PushBack(textures[i]->GetGraphicsObject());
388 const Graphics::TextureBinding textureBinding{textures[i]->GetGraphicsObject(), graphicsSampler, textureUnit};
389 textureBindings.push_back(textureBinding);
391 program.SetUniform1i(uniformLocation, textureUnit); // Get through shader reflection
397 if(textureBindings.size() > 0)
399 commandBuffer.BindTextures(textureBindings);
403 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
405 mFaceCullingMode = mode;
409 void Renderer::SetBlendingBitMask(uint32_t bitmask)
411 mBlendingOptions.SetBitmask(bitmask);
415 void Renderer::SetBlendColor(const Vector4& color)
417 mBlendingOptions.SetBlendColor(color);
421 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
423 mIndexedDrawFirstElement = firstElement;
427 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
429 mIndexedDrawElementsCount = elementsCount;
433 void Renderer::EnablePreMultipliedAlpha(bool enable)
435 mPremultipledAlphaEnabled = enable;
439 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
441 mDepthWriteMode = depthWriteMode;
445 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
447 mDepthTestMode = depthTestMode;
451 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
453 return mDepthWriteMode;
456 DepthTestMode::Type Renderer::GetDepthTestMode() const
458 return mDepthTestMode;
461 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
463 mDepthFunction = depthFunction;
467 DepthFunction::Type Renderer::GetDepthFunction() const
469 return mDepthFunction;
472 void Renderer::SetRenderMode(RenderMode::Type renderMode)
474 mStencilParameters.renderMode = renderMode;
478 RenderMode::Type Renderer::GetRenderMode() const
480 return mStencilParameters.renderMode;
483 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
485 mStencilParameters.stencilFunction = stencilFunction;
489 StencilFunction::Type Renderer::GetStencilFunction() const
491 return mStencilParameters.stencilFunction;
494 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
496 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
500 int Renderer::GetStencilFunctionMask() const
502 return mStencilParameters.stencilFunctionMask;
505 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
507 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
511 int Renderer::GetStencilFunctionReference() const
513 return mStencilParameters.stencilFunctionReference;
516 void Renderer::SetStencilMask(int stencilMask)
518 mStencilParameters.stencilMask = stencilMask;
522 int Renderer::GetStencilMask() const
524 return mStencilParameters.stencilMask;
527 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
529 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
533 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
535 return mStencilParameters.stencilOperationOnFail;
538 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
540 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
544 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
546 return mStencilParameters.stencilOperationOnZFail;
549 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
551 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
555 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
557 return mStencilParameters.stencilOperationOnZPass;
560 void Renderer::Upload()
562 mGeometry->Upload(*mGraphicsController);
565 bool Renderer::Render(Context& context,
566 BufferIndex bufferIndex,
567 const SceneGraph::NodeDataProvider& node,
568 const Matrix& modelMatrix,
569 const Matrix& modelViewMatrix,
570 const Matrix& viewMatrix,
571 const Matrix& projectionMatrix,
574 Vector<Graphics::Texture*>& boundTextures,
575 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
578 // Before doing anything test if the call happens in the right queue
579 if(mDrawCommands.empty() && queueIndex > 0)
585 std::vector<DevelRenderer::DrawCommand*> commands;
586 for(auto& cmd : mDrawCommands)
588 if(cmd.queue == queueIndex)
590 commands.emplace_back(&cmd);
594 // Have commands but nothing to be drawn - abort
595 if(!mDrawCommands.empty() && commands.empty())
600 // Create command buffer if not present
601 if(!mGraphicsCommandBuffer)
603 mGraphicsCommandBuffer = mGraphicsController->CreateCommandBuffer(
604 Graphics::CommandBufferCreateInfo()
605 .SetLevel(Graphics::CommandBufferLevel::SECONDARY),
610 mGraphicsCommandBuffer->Reset();
613 auto& commandBuffer = mGraphicsCommandBuffer;
616 if(!mDrawCommands.empty())
618 blend = (commands[0]->queue == DevelRenderer::RENDER_QUEUE_OPAQUE ? false : blend);
622 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
623 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
624 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
625 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
627 Graphics::PipelineStage::VERTEX_SHADER,
628 shaderData->GetSourceMode());
630 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
632 Graphics::PipelineStage::FRAGMENT_SHADER,
633 shaderData->GetSourceMode());
635 std::vector<Graphics::ShaderState> shaderStates{
636 Graphics::ShaderState()
637 .SetShader(vertexShader)
638 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
639 Graphics::ShaderState()
640 .SetShader(fragmentShader)
641 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
643 auto createInfo = Graphics::ProgramCreateInfo();
644 createInfo.SetShaderState(shaderStates);
646 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
647 Program* program = Program::New(*mProgramCache,
649 *mGraphicsController,
650 std::move(graphicsProgram),
651 (shaderData->GetHints() & Dali::Shader::Hint::MODIFIES_GEOMETRY) != 0x0);
655 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<void*>(&mRenderDataProvider->GetShader()));
659 // Temporarily create a pipeline here - this will be used for transporting
660 // topology, vertex format, attrs, rasterization state
661 mGraphicsPipeline = PrepareGraphicsPipeline(*program, instruction, blend, std::move(mGraphicsPipeline));
663 commandBuffer->BindPipeline(*mGraphicsPipeline.get());
665 BindTextures(*program, *commandBuffer.get(), boundTextures);
667 BuildUniformIndexMap(bufferIndex, node, size, *program);
669 WriteUniformBuffer(bufferIndex, *commandBuffer.get(), program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
671 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
672 // @todo We should detect this case much earlier to prevent unnecessary work
674 //@todo manage mDrawCommands in the same way as above command buffer?!
675 if(mDrawCommands.empty())
677 drawn = mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), mIndexedDrawFirstElement, mIndexedDrawElementsCount);
681 for(auto& cmd : commands)
683 // @todo This should generate a command buffer per cmd
684 // Tests WILL fail. (Temporarily commented out)
685 mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), cmd->firstIndex, cmd->elementCount);
689 // Command buffer contains Texture bindings, vertex bindings, index buffer binding, pipeline(vertex format)
690 // @todo We should return the command buffer(s) and let the calling method submit
691 // If not drawn, then don't add command buffer to submit info, and if empty, don't
696 Graphics::SubmitInfo submitInfo{{}, 0 | Graphics::SubmitFlagBits::FLUSH};
697 submitInfo.cmdBuffer.push_back(commandBuffer.get());
698 mGraphicsController->SubmitCommandBuffers(submitInfo);
705 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
707 // Check if the map has changed
708 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
710 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
712 if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
713 node.GetUniformMapChanged(bufferIndex) ||
714 mUniformIndexMap.Count() == 0 ||
717 // Reset shader pointer
718 mShaderChanged = false;
720 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
721 const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
723 uint32_t maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
724 mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
725 mUniformIndexMap.Resize(maxMaps);
727 uint32_t mapIndex = 0;
728 for(; mapIndex < uniformMap.Count(); ++mapIndex)
730 mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex].propertyPtr;
731 mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform(uniformMap[mapIndex].uniformName);
732 mUniformIndexMap[mapIndex].uniformName = uniformMap[mapIndex].uniformName;
733 mUniformIndexMap[mapIndex].uniformNameHash = uniformMap[mapIndex].uniformNameHash;
734 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
735 mUniformIndexMap[mapIndex].arrayIndex = uniformMap[mapIndex].arrayIndex;
738 for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
740 uint32_t uniformIndex = program.RegisterUniform(uniformMapNode[nodeMapIndex].uniformName);
742 for(uint32_t i = 0; i < uniformMap.Count(); ++i)
744 if(mUniformIndexMap[i].uniformIndex == uniformIndex)
746 mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
754 mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
755 mUniformIndexMap[mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
756 mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
757 mUniformIndexMap[mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
758 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
759 mUniformIndexMap[mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
764 mUniformIndexMap.Resize(mapIndex);
768 void Renderer::WriteUniformBuffer(
769 BufferIndex bufferIndex,
770 Graphics::CommandBuffer& commandBuffer,
772 const SceneGraph::RenderInstruction& instruction,
773 const SceneGraph::NodeDataProvider& node,
774 const Matrix& modelMatrix,
775 const Matrix& modelViewMatrix,
776 const Matrix& viewMatrix,
777 const Matrix& projectionMatrix,
781 uint32_t uniformBlockAllocationBytes{0u};
782 uint32_t uniformBlockMaxSize{0u};
783 uint32_t uboOffset{0u};
785 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
786 for(auto i = 0u; i < reflection.GetUniformBlockCount(); ++i)
788 auto blockSize = GetUniformBufferDataAlignment(reflection.GetUniformBlockSize(i));
789 if(uniformBlockMaxSize < blockSize)
791 uniformBlockMaxSize = blockSize;
793 uniformBlockAllocationBytes += blockSize;
796 auto pagedAllocation = ((uniformBlockAllocationBytes / UBO_PAGE_SIZE + 1u)) * UBO_PAGE_SIZE;
798 // Allocate twice memory as required by the uniform buffers
799 // todo: memory usage backlog to use optimal allocation
800 if(uniformBlockAllocationBytes && !mUniformBuffer[bufferIndex])
802 mUniformBuffer[bufferIndex] = mUniformBufferManager->AllocateUniformBuffer(pagedAllocation);
804 else if(uniformBlockAllocationBytes && (mUniformBuffer[bufferIndex]->GetSize() < pagedAllocation ||
805 (pagedAllocation < uint32_t(float(mUniformBuffer[bufferIndex]->GetSize()) * UBO_SHRINK_THRESHOLD))))
807 mUniformBuffer[bufferIndex]->Reserve(pagedAllocation);
811 if(mUniformBuffer[bufferIndex])
813 mUniformBuffer[bufferIndex]->Fill(0, 0u, 0u);
816 // update the uniform buffer
817 // pass shared UBO and offset, return new offset for next item to be used
818 // don't process bindings if there are no uniform buffers allocated
819 auto ubo = mUniformBuffer[bufferIndex].get();
822 auto uboCount = reflection.GetUniformBlockCount();
823 mUniformBufferBindings.resize(uboCount);
825 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
827 // Write default uniforms
828 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *ubo, *bindings, modelMatrix);
829 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *ubo, *bindings, viewMatrix);
830 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *ubo, *bindings, projectionMatrix);
831 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *ubo, *bindings, modelViewMatrix);
833 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
834 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
836 Matrix modelViewProjectionMatrix(false);
837 Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
838 WriteDefaultUniform(mvpUniformInfo, *ubo, *bindings, modelViewProjectionMatrix);
841 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
842 if(normalUniformInfo && !normalUniformInfo->name.empty())
844 Matrix3 normalMatrix(modelViewMatrix);
845 normalMatrix.Invert();
846 normalMatrix.Transpose();
847 WriteDefaultUniform(normalUniformInfo, *ubo, *bindings, normalMatrix);
851 const Vector4& color = node.GetRenderColor(bufferIndex);
852 if(mPremultipledAlphaEnabled)
854 float alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
855 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
859 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
861 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *ubo, *bindings, finalColor);
863 // Write uniforms from the uniform map
864 FillUniformBuffer(*program, instruction, *ubo, bindings, uboOffset, bufferIndex);
866 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
867 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *ubo, *bindings, size);
869 commandBuffer.BindUniformBuffers(*bindings);
874 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data)
876 if(uniformInfo && !uniformInfo->name.empty())
878 WriteUniform(ubo, bindings, *uniformInfo, data);
885 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data)
887 WriteUniform(ubo, bindings, uniformInfo, &data, sizeof(T));
890 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
892 ubo.Write(data, size, bindings[uniformInfo.bufferIndex].offset + uniformInfo.offset);
895 void Renderer::FillUniformBuffer(Program& program,
896 const SceneGraph::RenderInstruction& instruction,
897 Render::UniformBuffer& ubo,
898 std::vector<Graphics::UniformBufferBinding>*& outBindings,
900 BufferIndex updateBufferIndex)
902 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
903 auto uboCount = reflection.GetUniformBlockCount();
906 uint32_t dataOffset = offset;
907 for(auto i = 0u; i < uboCount; ++i)
909 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
910 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
911 mUniformBufferBindings[i].offset = dataOffset;
913 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
914 mUniformBufferBindings[i].buffer = ubo.GetBuffer();
916 for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
917 end = mUniformIndexMap.End();
921 // @todo This means parsing the uniform string every frame. Instead, store the array index if present.
922 int arrayIndex = (*iter).arrayIndex;
924 auto uniformInfo = Graphics::UniformInfo{};
925 auto uniformFound = program.GetUniform((*iter).uniformName.GetCString(),
926 (*iter).uniformNameHashNoArray ? (*iter).uniformNameHashNoArray
927 : (*iter).uniformNameHash,
932 auto dst = mUniformBufferBindings[uniformInfo.bufferIndex].offset + uniformInfo.offset;
934 switch((*iter).propertyValue->GetType())
936 case Property::Type::BOOLEAN:
938 ubo.Write(&(*iter).propertyValue->GetBoolean(updateBufferIndex),
940 dst + static_cast<uint32_t>(sizeof(bool)) * arrayIndex);
943 case Property::Type::INTEGER:
945 ubo.Write(&(*iter).propertyValue->GetInteger(updateBufferIndex),
947 dst + static_cast<int32_t>(sizeof(int32_t)) * arrayIndex);
950 case Property::Type::FLOAT:
952 ubo.Write(&(*iter).propertyValue->GetFloat(updateBufferIndex),
954 dst + static_cast<uint32_t>(sizeof(float)) * arrayIndex);
957 case Property::Type::VECTOR2:
959 ubo.Write(&(*iter).propertyValue->GetVector2(updateBufferIndex),
961 dst + static_cast<uint32_t>(sizeof(Vector2)) * arrayIndex);
964 case Property::Type::VECTOR3:
966 ubo.Write(&(*iter).propertyValue->GetVector3(updateBufferIndex),
968 dst + static_cast<uint32_t>(sizeof(Vector3)) * arrayIndex);
971 case Property::Type::VECTOR4:
973 ubo.Write(&(*iter).propertyValue->GetVector4(updateBufferIndex),
975 dst + static_cast<uint32_t>(sizeof(Vector4)) * arrayIndex);
978 case Property::Type::MATRIX:
980 ubo.Write(&(*iter).propertyValue->GetMatrix(updateBufferIndex),
982 dst + static_cast<uint32_t>(sizeof(Matrix)) * arrayIndex);
985 case Property::Type::MATRIX3:
987 // todo: handle data padding properly
990 //const auto& matrix = &(*iter).propertyValue->GetMatrix3(updateBufferIndex);
991 //for(int i = 0; i < 3; ++i)
993 //ubo.Write(&matrix->AsFloat()[i * 3],
994 // sizeof(float) * 3,
995 // dst + (i * static_cast<uint32_t>(sizeof(Vector4))));
998 ubo.Write(&(*iter).propertyValue->GetMatrix3(updateBufferIndex),
1000 dst + static_cast<uint32_t>(sizeof(Matrix3)) * arrayIndex);
1010 // write output bindings
1011 outBindings = &mUniformBufferBindings;
1014 offset = dataOffset;
1017 void Renderer::SetSortAttributes(BufferIndex bufferIndex,
1018 SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
1020 sortAttributes.shader = &(mRenderDataProvider->GetShader());
1021 sortAttributes.geometry = mGeometry;
1024 void Renderer::SetShaderChanged(bool value)
1026 mShaderChanged = value;
1029 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
1037 if(mShaderChanged || mUpdateAttributeLocations || mGeometry->AttributesChanged())
1042 for(const auto& texture : mRenderDataProvider->GetTextures())
1044 if(texture && texture->IsNativeImage())
1050 uint64_t hash = 0xc70f6907UL;
1051 const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
1052 for(const auto& uniformProperty : uniformMapNode)
1054 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1057 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
1058 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
1059 for(const auto& uniformProperty : uniformMap)
1061 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1064 if(mUniformsHash != hash)
1066 mUniformsHash = hash;
1073 Graphics::UniquePtr<Graphics::Pipeline> Renderer::PrepareGraphicsPipeline(
1075 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
1077 Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
1079 Graphics::InputAssemblyState inputAssemblyState{};
1080 Graphics::VertexInputState vertexInputState{};
1081 Graphics::ProgramState programState{};
1082 uint32_t bindingIndex{0u};
1084 if(mUpdateAttributeLocations || mGeometry->AttributesChanged())
1086 mAttributeLocations.Clear();
1087 mUpdateAttributeLocations = true;
1090 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
1096 for(auto&& vertexBuffer : mGeometry->GetVertexBuffers())
1098 const VertexBuffer::Format& vertexFormat = *vertexBuffer->GetFormat();
1100 vertexInputState.bufferBindings.emplace_back(vertexFormat.size, // stride
1101 Graphics::VertexInputRate::PER_VERTEX);
1103 const uint32_t attributeCount = vertexBuffer->GetAttributeCount();
1104 for(uint32_t i = 0; i < attributeCount; ++i)
1106 if(mUpdateAttributeLocations)
1108 auto attributeName = vertexBuffer->GetAttributeName(i);
1109 int32_t pLocation = reflection.GetVertexAttributeLocation(std::string(attributeName.GetStringView()));
1112 DALI_LOG_WARNING("Attribute not found in the shader: %s\n", attributeName.GetCString());
1114 mAttributeLocations.PushBack(pLocation);
1117 uint32_t location = static_cast<uint32_t>(mAttributeLocations[base + i]);
1119 vertexInputState.attributes.emplace_back(location,
1121 vertexFormat.components[i].offset,
1122 GetPropertyVertexFormat(vertexFormat.components[i].type));
1124 base += attributeCount;
1127 mUpdateAttributeLocations = false;
1130 inputAssemblyState.SetTopology(mGeometry->GetTopology());
1133 programState.SetProgram(program.GetGraphicsProgram());
1135 Graphics::RasterizationState rasterizationState{};
1137 //Set cull face mode
1138 const Dali::Internal::SceneGraph::Camera* cam = instruction.GetCamera();
1139 if(cam->GetReflectionUsed())
1141 auto adjFaceCullingMode = mFaceCullingMode;
1142 switch(mFaceCullingMode)
1144 case FaceCullingMode::Type::FRONT:
1146 adjFaceCullingMode = FaceCullingMode::Type::BACK;
1149 case FaceCullingMode::Type::BACK:
1151 adjFaceCullingMode = FaceCullingMode::Type::FRONT;
1156 // nothing to do, leave culling as it is
1159 rasterizationState.SetCullMode(ConvertCullFace(adjFaceCullingMode));
1163 rasterizationState.SetCullMode(ConvertCullFace(mFaceCullingMode));
1166 rasterizationState.SetFrontFace(Graphics::FrontFace::COUNTER_CLOCKWISE);
1171 switch(mGeometry->GetTopology())
1173 case Graphics::PrimitiveTopology::TRIANGLE_LIST:
1174 case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
1175 case Graphics::PrimitiveTopology::TRIANGLE_FAN:
1176 rasterizationState.SetPolygonMode(Graphics::PolygonMode::FILL);
1178 case Graphics::PrimitiveTopology::LINE_LIST:
1179 case Graphics::PrimitiveTopology::LINE_LOOP:
1180 case Graphics::PrimitiveTopology::LINE_STRIP:
1181 rasterizationState.SetPolygonMode(Graphics::PolygonMode::LINE);
1183 case Graphics::PrimitiveTopology::POINT_LIST:
1184 rasterizationState.SetPolygonMode(Graphics::PolygonMode::POINT);
1188 // @todo How to signal a blend barrier is needed?
1189 //if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1191 // context.BlendBarrier();
1194 Graphics::ColorBlendState colorBlendState{};
1195 colorBlendState.SetBlendEnable(false);
1199 colorBlendState.SetBlendEnable(true);
1201 Graphics::BlendOp rgbOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1202 Graphics::BlendOp alphaOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1203 if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1205 if(rgbOp != alphaOp)
1207 DALI_LOG_ERROR("Advanced Blend Equation MUST be applied by using BlendEquation.\n");
1213 .SetSrcColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorRgb()))
1214 .SetSrcAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorAlpha()))
1215 .SetDstColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorRgb()))
1216 .SetDstAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorAlpha()))
1217 .SetColorBlendOp(rgbOp)
1218 .SetAlphaBlendOp(alphaOp);
1220 // Blend color is optional and rarely used
1221 Vector4* blendColor = const_cast<Vector4*>(mBlendingOptions.GetBlendColor());
1224 colorBlendState.SetBlendConstants(blendColor->AsFloat());
1228 // Take the program into use so we can send uniforms to it
1229 // @todo Remove this call entirely!
1234 // Create a new pipeline
1235 // @todo Passed as pointers - shallow copy will break. Implementation MUST deep copy.
1236 return mGraphicsController->CreatePipeline(
1237 Graphics::PipelineCreateInfo()
1238 .SetInputAssemblyState(&inputAssemblyState)
1239 .SetVertexInputState(&vertexInputState)
1240 .SetRasterizationState(&rasterizationState)
1241 .SetColorBlendState(&colorBlendState)
1242 .SetProgramState(&programState)
1243 .SetNextExtension(&mLegacyProgram),
1244 std::move(oldPipeline));
1247 } // namespace Render
1249 } // namespace Internal