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.
18 #include <dali/internal/graphics/gles-impl/egl-graphics-controller.h>
21 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/integration-api/gl-abstraction.h>
24 #include <dali/integration-api/gl-defines.h>
25 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
26 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
27 #include <dali/internal/graphics/gles-impl/gles-graphics-render-pass.h>
28 #include <dali/internal/graphics/gles-impl/gles-graphics-render-target.h>
29 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
30 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
31 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
32 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
33 #include <dali/public-api/common/dali-common.h>
34 #include "gles-graphics-program.h"
36 // Uncomment the following define to turn on frame dumping
37 //#define ENABLE_COMMAND_BUFFER_FRAME_DUMP 1
38 #include <dali/internal/graphics/gles-impl/egl-graphics-controller-debug.h>
41 namespace Dali::Graphics
46 * @brief Custom deleter for all Graphics objects created
47 * with use of the Controller.
49 * When Graphics object dies the unique pointer (Graphics::UniquePtr)
50 * doesn't destroy it directly but passes the ownership back
51 * to the Controller. The GLESDeleter is responsible for passing
52 * the object to the discard queue (by calling Resource::DiscardResource()).
57 GLESDeleter() = default;
59 void operator()(T* object)
61 // Discard resource (add it to discard queue)
62 object->DiscardResource();
67 * @brief Helper function allocating graphics object
69 * @param[in] info Create info structure
70 * @param[in] controller Controller object
71 * @param[out] out Unique pointer to the return object
73 template<class GLESType, class GfxCreateInfo, class T>
74 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
77 using Type = typename T::element_type;
78 using UPtr = Graphics::UniquePtr<Type>;
79 if(info.allocationCallbacks)
81 auto* memory = info.allocationCallbacks->allocCallback(
84 info.allocationCallbacks->userData);
85 return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
87 else // Use standard allocator
89 return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
93 template<class T0, class T1>
94 T0* CastObject(T1* apiObject)
96 return static_cast<T0*>(apiObject);
101 EglGraphicsController::~EglGraphicsController() = default;
103 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
105 DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #1\n");
106 mGlAbstraction = &glAbstraction;
107 mContext = std::make_unique<GLES::Context>(*this);
108 mCurrentContext = mContext.get();
111 void EglGraphicsController::Initialize(Integration::GlSyncAbstraction& glSyncAbstraction,
112 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
113 Internal::Adaptor::GraphicsInterface& graphicsInterface)
115 DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #2\n");
116 mGlSyncAbstraction = &glSyncAbstraction;
117 mGlContextHelperAbstraction = &glContextHelperAbstraction;
118 mGraphics = &graphicsInterface;
121 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
123 for(auto& cmdbuf : submitInfo.cmdBuffer)
125 // Push command buffers
126 mCommandQueue.push(static_cast<GLES::CommandBuffer*>(cmdbuf));
129 // If flush bit set, flush all pending tasks
130 if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
136 void EglGraphicsController::PresentRenderTarget(RenderTarget* renderTarget)
138 // Use command buffer to execute presentation (we should pool it)
139 CommandBufferCreateInfo info;
140 info.SetLevel(CommandBufferLevel::PRIMARY);
141 info.fixedCapacity = 1; // only one command
142 auto presentCommandBuffer = new GLES::CommandBuffer(info, *this);
143 presentCommandBuffer->PresentRenderTarget(static_cast<GLES::RenderTarget*>(renderTarget));
144 SubmitInfo submitInfo;
145 submitInfo.cmdBuffer = {presentCommandBuffer};
146 submitInfo.flags = 0 | SubmitFlagBits::FLUSH;
147 SubmitCommandBuffers(submitInfo);
150 void EglGraphicsController::ResolvePresentRenderTarget(GLES::RenderTarget* renderTarget)
152 auto* rt = static_cast<GLES::RenderTarget*>(renderTarget);
153 if(rt->GetCreateInfo().surface)
155 auto* surfaceInterface = reinterpret_cast<Dali::RenderSurfaceInterface*>(rt->GetCreateInfo().surface);
156 surfaceInterface->MakeContextCurrent();
157 surfaceInterface->PostRender();
161 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
163 DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
164 return *mGlAbstraction;
167 Integration::GlSyncAbstraction& EglGraphicsController::GetGlSyncAbstraction()
169 DALI_ASSERT_DEBUG(mGlSyncAbstraction && "Graphics controller not initialized");
170 return *mGlSyncAbstraction;
173 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
175 DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
176 return *mGlContextHelperAbstraction;
179 Graphics::UniquePtr<CommandBuffer> EglGraphicsController::CreateCommandBuffer(
180 const CommandBufferCreateInfo& commandBufferCreateInfo,
181 Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
183 return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
186 Graphics::UniquePtr<RenderPass> EglGraphicsController::CreateRenderPass(const RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<RenderPass>&& oldRenderPass)
188 return NewObject<GLES::RenderPass>(renderPassCreateInfo, *this, std::move(oldRenderPass));
191 Graphics::UniquePtr<Texture>
192 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
194 return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
197 Graphics::UniquePtr<Buffer> EglGraphicsController::CreateBuffer(
198 const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
200 return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
203 Graphics::UniquePtr<Framebuffer> EglGraphicsController::CreateFramebuffer(
204 const FramebufferCreateInfo& framebufferCreateInfo, Graphics::UniquePtr<Framebuffer>&& oldFramebuffer)
206 return NewObject<GLES::Framebuffer>(framebufferCreateInfo, *this, std::move(oldFramebuffer));
209 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(
210 const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
212 // Create pipeline cache if needed
215 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
218 return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
221 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(
222 const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
224 // Create program cache if needed
227 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
230 return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
233 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
235 return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
238 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
240 return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
243 Graphics::UniquePtr<RenderTarget> EglGraphicsController::CreateRenderTarget(const RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<RenderTarget>&& oldRenderTarget)
245 return NewObject<GLES::RenderTarget>(renderTargetCreateInfo, *this, std::move(oldRenderTarget));
248 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
250 return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
253 void EglGraphicsController::CreateSurfaceContext(Dali::RenderSurfaceInterface* surface)
255 std::unique_ptr<GLES::Context> context = std::make_unique<GLES::Context>(*this);
256 mSurfaceContexts.push_back(std::move(std::make_pair(surface, std::move(context))));
259 void EglGraphicsController::DeleteSurfaceContext(Dali::RenderSurfaceInterface* surface)
261 mSurfaceContexts.erase(std::remove_if(
262 mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return surface == iter.first; }),
263 mSurfaceContexts.end());
266 void EglGraphicsController::ActivateResourceContext()
268 mCurrentContext = mContext.get();
271 void EglGraphicsController::ActivateSurfaceContext(Dali::RenderSurfaceInterface* surface)
273 if(surface && mGraphics->IsResourceContextSupported())
275 auto iter = std::find_if(mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) {
276 return (iter.first == surface);
279 if(iter != mSurfaceContexts.end())
281 mCurrentContext = iter->second.get();
286 void EglGraphicsController::AddTexture(GLES::Texture& texture)
288 // Assuming we are on the correct context
289 mCreateTextureQueue.push(&texture);
292 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
294 // Assuming we are on the correct context
295 mCreateBufferQueue.push(&buffer);
298 void EglGraphicsController::AddFramebuffer(GLES::Framebuffer& framebuffer)
300 // Assuming we are on the correct context
301 mCreateFramebufferQueue.push(&framebuffer);
304 void EglGraphicsController::ProcessDiscardQueues()
307 ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
310 ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
312 // Process Framebuffers
313 ProcessDiscardQueue<GLES::Framebuffer>(mDiscardFramebufferQueue);
316 ProcessDiscardQueue<GLES::Pipeline>(mDiscardPipelineQueue);
319 ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
322 ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
325 ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
327 // Process command buffers
328 ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
331 void EglGraphicsController::ProcessCreateQueues()
334 ProcessCreateQueue(mCreateTextureQueue);
337 ProcessCreateQueue(mCreateBufferQueue);
339 // Process framebuffers
340 ProcessCreateQueue(mCreateFramebufferQueue);
343 void EglGraphicsController::ProcessCommandBuffer(const GLES::CommandBuffer& commandBuffer)
345 for(auto& cmd : commandBuffer.GetCommands())
350 case GLES::CommandType::FLUSH:
352 // Nothing to do here
355 case GLES::CommandType::BIND_TEXTURES:
357 mCurrentContext->BindTextures(cmd.bindTextures.textureBindings);
360 case GLES::CommandType::BIND_VERTEX_BUFFERS:
362 auto& bindings = cmd.bindVertexBuffers.vertexBufferBindings;
363 mCurrentContext->BindVertexBuffers(bindings);
366 case GLES::CommandType::BIND_UNIFORM_BUFFER:
368 auto& bindings = cmd.bindUniformBuffers;
369 mCurrentContext->BindUniformBuffers(bindings.uniformBufferBindings, bindings.standaloneUniformsBufferBinding);
372 case GLES::CommandType::BIND_INDEX_BUFFER:
374 mCurrentContext->BindIndexBuffer(cmd.bindIndexBuffer);
377 case GLES::CommandType::BIND_SAMPLERS:
381 case GLES::CommandType::BIND_PIPELINE:
383 auto pipeline = static_cast<const GLES::Pipeline*>(cmd.bindPipeline.pipeline);
384 mCurrentContext->BindPipeline(pipeline);
387 case GLES::CommandType::DRAW:
389 mCurrentContext->Flush(false, cmd.draw);
392 case GLES::CommandType::DRAW_INDEXED:
394 mCurrentContext->Flush(false, cmd.draw);
397 case GLES::CommandType::DRAW_INDEXED_INDIRECT:
399 mCurrentContext->Flush(false, cmd.draw);
402 case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
404 mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
407 case GLES::CommandType::SET_SCISSOR_TEST:
409 if(cmd.scissorTest.enable)
411 mGlAbstraction->Enable(GL_SCISSOR_TEST);
415 mGlAbstraction->Disable(GL_SCISSOR_TEST);
419 case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
421 mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
425 case GLES::CommandType::SET_COLOR_MASK:
427 mCurrentContext->ColorMask(cmd.colorMask.enabled);
430 case GLES::CommandType::CLEAR_STENCIL_BUFFER:
432 mCurrentContext->ClearStencilBuffer();
435 case GLES::CommandType::CLEAR_DEPTH_BUFFER:
437 mCurrentContext->ClearDepthBuffer();
441 case GLES::CommandType::SET_STENCIL_TEST_ENABLE:
443 mCurrentContext->SetStencilTestEnable(cmd.stencilTest.enabled);
447 case GLES::CommandType::SET_STENCIL_FUNC:
449 mCurrentContext->StencilFunc(cmd.stencilFunc.compareOp,
450 cmd.stencilFunc.reference,
451 cmd.stencilFunc.compareMask);
455 case GLES::CommandType::SET_STENCIL_WRITE_MASK:
457 mCurrentContext->StencilMask(cmd.stencilWriteMask.mask);
461 case GLES::CommandType::SET_STENCIL_OP:
463 mCurrentContext->StencilOp(cmd.stencilOp.failOp,
464 cmd.stencilOp.depthFailOp,
465 cmd.stencilOp.passOp);
469 case GLES::CommandType::SET_DEPTH_COMPARE_OP:
471 mCurrentContext->SetDepthCompareOp(cmd.depth.compareOp);
474 case GLES::CommandType::SET_DEPTH_TEST_ENABLE:
476 mCurrentContext->SetDepthTestEnable(cmd.depth.testEnabled);
479 case GLES::CommandType::SET_DEPTH_WRITE_ENABLE:
481 mCurrentContext->SetDepthWriteEnable(cmd.depth.writeEnabled);
485 case GLES::CommandType::BEGIN_RENDERPASS:
487 auto& renderTarget = *cmd.beginRenderPass.renderTarget;
488 const auto& targetInfo = renderTarget.GetCreateInfo();
490 if(targetInfo.surface)
492 // switch to surface context
493 mGraphics->ActivateSurfaceContext(static_cast<Dali::RenderSurfaceInterface*>(targetInfo.surface));
495 else if(targetInfo.framebuffer)
497 // switch to resource context
498 mGraphics->ActivateResourceContext();
501 mCurrentContext->BeginRenderPass(cmd.beginRenderPass);
504 case GLES::CommandType::END_RENDERPASS:
506 mCurrentContext->EndRenderPass();
509 case GLES::CommandType::PRESENT_RENDER_TARGET:
511 ResolvePresentRenderTarget(cmd.presentRenderTarget.targetToPresent);
513 // push this command buffer to the discard queue
514 mDiscardCommandBufferQueue.push(const_cast<GLES::CommandBuffer*>(&commandBuffer));
517 case GLES::CommandType::EXECUTE_COMMAND_BUFFERS:
519 // Process secondary command buffers
520 // todo: check validity of the secondaries
521 // there are operations which are illigal to be done
522 // within secondaries.
523 for(auto& buf : cmd.executeCommandBuffers.buffers)
525 ProcessCommandBuffer(*static_cast<const GLES::CommandBuffer*>(buf));
533 void EglGraphicsController::ProcessCommandQueues()
535 // TODO: command queue per context, sync between queues should be
537 currentFramebuffer = nullptr;
541 while(!mCommandQueue.empty())
543 auto cmdBuf = mCommandQueue.front();
545 DUMP_FRAME_COMMAND_BUFFER(cmdBuf);
546 ProcessCommandBuffer(*cmdBuf);
552 void EglGraphicsController::ProcessTextureUpdateQueue()
554 while(!mTextureUpdateRequests.empty())
556 TextureUpdateRequest& request = mTextureUpdateRequests.front();
558 auto& info = request.first;
559 auto& source = request.second;
561 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
563 // GPU memory must be already allocated.
565 // Check if it needs conversion
566 auto* texture = static_cast<GLES::Texture*>(info.dstTexture);
567 const auto& createInfo = texture->GetCreateInfo();
568 auto srcFormat = GLES::GLTextureFormatType(info.srcFormat).format;
569 auto destFormat = GLES::GLTextureFormatType(createInfo.format).format;
570 auto destType = GLES::GLTextureFormatType(createInfo.format).type;
572 // From render-texture.cpp
573 const bool isSubImage(info.dstOffset2D.x != 0 || info.dstOffset2D.y != 0 ||
574 info.srcExtent2D.width != (createInfo.size.width / (1 << info.level)) ||
575 info.srcExtent2D.height != (createInfo.size.height / (1 << info.level)));
577 auto* sourceBuffer = reinterpret_cast<uint8_t*>(source.memorySource.memory);
578 std::vector<uint8_t> tempBuffer;
579 if(mGlAbstraction->TextureRequiresConverting(srcFormat, destFormat, isSubImage))
581 // Convert RGB to RGBA if necessary.
582 texture->TryConvertPixelData(source.memorySource.memory, info.srcFormat, createInfo.format, info.srcSize, info.srcExtent2D.width, info.srcExtent2D.height, tempBuffer);
583 sourceBuffer = &tempBuffer[0];
586 // Calculate the maximum mipmap level for the texture
587 texture->SetMaxMipMapLevel(std::max(texture->GetMaxMipMapLevel(), info.level));
589 switch(createInfo.textureType)
592 case Graphics::TextureType::TEXTURE_2D:
594 mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
596 mGlAbstraction->BindTexture(GL_TEXTURE_2D, texture->GetGLTexture());
598 mGlAbstraction->TexSubImage2D(GL_TEXTURE_2D,
602 info.srcExtent2D.width,
603 info.srcExtent2D.height,
610 case Graphics::TextureType::TEXTURE_CUBEMAP:
612 mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
614 mGlAbstraction->BindTexture(GL_TEXTURE_CUBE_MAP, texture->GetGLTexture());
616 mGlAbstraction->TexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + info.layer,
620 info.srcExtent2D.width,
621 info.srcExtent2D.height,
634 // free staging memory
635 free(source.memorySource.memory);
639 // TODO: other sources
642 mTextureUpdateRequests.pop();
646 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>& updateInfoList,
647 const std::vector<TextureUpdateSourceInfo>& sourceList)
650 for(auto& info : updateInfoList)
652 mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
653 auto& pair = mTextureUpdateRequests.back();
654 switch(pair.second.sourceType)
656 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
658 auto& info = pair.first;
659 auto& source = pair.second;
661 // allocate staging memory and copy the data
662 // TODO: using PBO with GLES3, this is just naive
665 char* stagingBuffer = reinterpret_cast<char*>(malloc(info.srcSize));
666 std::copy(&reinterpret_cast<char*>(source.memorySource.memory)[info.srcOffset],
667 reinterpret_cast<char*>(source.memorySource.memory) + info.srcSize,
670 // store staging buffer
671 source.memorySource.memory = stagingBuffer;
674 case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
676 // TODO, with PBO support
679 case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
681 // TODO texture 2 texture in-GPU copy
688 void EglGraphicsController::ProcessTextureMipmapGenerationQueue()
690 while(!mTextureMipmapGenerationRequests.empty())
692 auto* texture = mTextureMipmapGenerationRequests.front();
694 mGlAbstraction->BindTexture(texture->GetGlTarget(), texture->GetGLTexture());
695 mGlAbstraction->GenerateMipmap(texture->GetGlTarget());
697 mTextureMipmapGenerationRequests.pop();
701 void EglGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
703 mTextureMipmapGenerationRequests.push(static_cast<const GLES::Texture*>(&texture));
706 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
708 mGraphics->ActivateResourceContext();
710 // Mapping buffer requires the object to be created NOW
711 // Workaround - flush now, otherwise there will be given a staging buffer
712 // in case when the buffer is not there yet
713 ProcessCreateQueues();
715 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
717 return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
721 return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
725 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
727 return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
730 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
732 return *mPipelineCache;
735 } // namespace Dali::Graphics