2 * Copyright (c) 2023 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/public-api/common/dali-common.h>
24 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/integration-api/gl-abstraction.h>
27 #include <dali/integration-api/gl-defines.h>
28 #include <dali/integration-api/graphics-sync-abstraction.h>
29 #include <dali/integration-api/pixel-data-integ.h>
30 #include <dali/internal/graphics/gles-impl/egl-sync-object.h>
31 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
32 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
33 #include <dali/internal/graphics/gles-impl/gles-graphics-program.h>
34 #include <dali/internal/graphics/gles-impl/gles-graphics-render-pass.h>
35 #include <dali/internal/graphics/gles-impl/gles-graphics-render-target.h>
36 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
37 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
38 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
39 #include <dali/internal/graphics/gles-impl/gles-sync-object.h>
40 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
41 #include <dali/internal/graphics/gles/egl-sync-implementation.h>
43 #include <dali/internal/graphics/gles/egl-graphics.h>
47 // Uncomment the following define to turn on frame dumping
48 //#define ENABLE_COMMAND_BUFFER_FRAME_DUMP 1
49 #include <dali/internal/graphics/gles-impl/egl-graphics-controller-debug.h>
52 namespace Dali::Graphics
57 * @brief Custom deleter for all Graphics objects created
58 * with use of the Controller.
60 * When Graphics object dies the unique pointer (Graphics::UniquePtr)
61 * doesn't destroy it directly but passes the ownership back
62 * to the Controller. The GLESDeleter is responsible for passing
63 * the object to the discard queue (by calling Resource::DiscardResource()).
68 GLESDeleter() = default;
70 void operator()(T* object)
72 // Discard resource (add it to discard queue)
73 object->DiscardResource();
78 * @brief Helper function allocating graphics object
80 * @param[in] info Create info structure
81 * @param[in] controller Controller object
82 * @param[out] out Unique pointer to the return object
84 template<class GLESType, class GfxCreateInfo, class T>
85 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
88 using Type = typename T::element_type;
89 using UPtr = Graphics::UniquePtr<Type>;
90 if(info.allocationCallbacks)
92 auto* memory = info.allocationCallbacks->allocCallback(
95 info.allocationCallbacks->userData);
96 return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
98 else // Use standard allocator
100 // We are given all object for recycling
103 auto reusedObject = oldObject.release();
104 // If succeeded, attach the object to the unique_ptr and return it back
105 if(static_cast<GLESType*>(reusedObject)->TryRecycle(info, controller))
107 return UPtr(reusedObject, GLESDeleter<GLESType>());
111 // can't reuse so kill object by giving it back to original
113 oldObject.reset(reusedObject);
117 // Create brand new object
118 return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
122 template<class T0, class T1>
123 T0* CastObject(T1* apiObject)
125 return static_cast<T0*>(apiObject);
128 // Maximum size of texture upload buffer.
129 const uint32_t TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB = 1;
133 EglGraphicsController::EglGraphicsController()
134 : mTextureDependencyChecker(*this),
139 EglGraphicsController::~EglGraphicsController()
141 while(!mPresentationCommandBuffers.empty())
143 auto presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
144 delete presentCommandBuffer;
145 mPresentationCommandBuffers.pop();
149 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
151 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 1\n");
152 mGlAbstraction = &glAbstraction;
153 mContext = std::make_unique<GLES::Context>(*this);
154 mCurrentContext = mContext.get();
157 void EglGraphicsController::Initialize(Integration::GraphicsSyncAbstraction& syncImplementation,
158 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
159 Internal::Adaptor::GraphicsInterface& graphicsInterface)
161 DALI_LOG_RELEASE_INFO("Initializing Graphics Controller Phase 2\n");
162 auto* syncImplPtr = static_cast<Internal::Adaptor::EglSyncImplementation*>(&syncImplementation);
164 mEglSyncImplementation = syncImplPtr;
165 mGlContextHelperAbstraction = &glContextHelperAbstraction;
166 mGraphics = &graphicsInterface;
169 void EglGraphicsController::FrameStart()
171 mCapacity = 0; // Reset the command buffer capacity at the start of the frame.
174 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
176 for(auto& cmdbuf : submitInfo.cmdBuffer)
178 // Push command buffers
179 auto* commandBuffer = static_cast<GLES::CommandBuffer*>(cmdbuf);
180 mCapacity += commandBuffer->GetCapacity();
181 mCommandQueue.push(commandBuffer);
184 // If flush bit set, flush all pending tasks
185 if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
191 void EglGraphicsController::WaitIdle()
196 void EglGraphicsController::PresentRenderTarget(RenderTarget* renderTarget)
198 GLES::CommandBuffer* presentCommandBuffer{nullptr};
199 if(mPresentationCommandBuffers.empty())
201 CommandBufferCreateInfo info;
202 info.SetLevel(CommandBufferLevel::PRIMARY);
203 info.fixedCapacity = 1; // only one command
204 presentCommandBuffer = new GLES::CommandBuffer(info, *this);
208 presentCommandBuffer = const_cast<GLES::CommandBuffer*>(mPresentationCommandBuffers.front());
209 presentCommandBuffer->Reset();
210 mPresentationCommandBuffers.pop();
212 presentCommandBuffer->PresentRenderTarget(static_cast<GLES::RenderTarget*>(renderTarget));
213 SubmitInfo submitInfo;
214 submitInfo.cmdBuffer = {presentCommandBuffer};
215 submitInfo.flags = 0 | SubmitFlagBits::FLUSH;
216 SubmitCommandBuffers(submitInfo);
219 void EglGraphicsController::ResolvePresentRenderTarget(GLES::RenderTarget* renderTarget)
221 mCurrentContext->InvalidateDepthStencilBuffers();
223 auto* rt = static_cast<GLES::RenderTarget*>(renderTarget);
224 if(rt->GetCreateInfo().surface)
226 auto* surfaceInterface = reinterpret_cast<Dali::RenderSurfaceInterface*>(rt->GetCreateInfo().surface);
227 surfaceInterface->MakeContextCurrent();
228 surfaceInterface->PostRender();
232 void EglGraphicsController::PostRender()
234 mTextureDependencyChecker.Reset();
235 mSyncPool.AgeSyncObjects();
238 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
240 DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
241 return *mGlAbstraction;
244 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
246 DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
247 return *mGlContextHelperAbstraction;
250 Internal::Adaptor::EglSyncImplementation& EglGraphicsController::GetEglSyncImplementation()
252 DALI_ASSERT_DEBUG(mEglSyncImplementation && "Sync implementation not initialized");
253 return *mEglSyncImplementation;
256 Graphics::UniquePtr<CommandBuffer> EglGraphicsController::CreateCommandBuffer(
257 const CommandBufferCreateInfo& commandBufferCreateInfo,
258 Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
260 return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
263 Graphics::UniquePtr<RenderPass> EglGraphicsController::CreateRenderPass(const RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<RenderPass>&& oldRenderPass)
265 return NewObject<GLES::RenderPass>(renderPassCreateInfo, *this, std::move(oldRenderPass));
268 Graphics::UniquePtr<Texture>
269 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
271 return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
274 Graphics::UniquePtr<Buffer> EglGraphicsController::CreateBuffer(
275 const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
277 return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
280 Graphics::UniquePtr<Framebuffer> EglGraphicsController::CreateFramebuffer(
281 const FramebufferCreateInfo& framebufferCreateInfo, Graphics::UniquePtr<Framebuffer>&& oldFramebuffer)
283 return NewObject<GLES::Framebuffer>(framebufferCreateInfo, *this, std::move(oldFramebuffer));
286 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(
287 const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
289 // Create pipeline cache if needed
292 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
295 return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
298 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(
299 const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
301 // Create program cache if needed
304 mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
307 return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
310 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
312 return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
315 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
317 return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
320 Graphics::UniquePtr<RenderTarget> EglGraphicsController::CreateRenderTarget(const RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<RenderTarget>&& oldRenderTarget)
322 return NewObject<GLES::RenderTarget>(renderTargetCreateInfo, *this, std::move(oldRenderTarget));
325 Graphics::UniquePtr<SyncObject> EglGraphicsController::CreateSyncObject(const SyncObjectCreateInfo& syncObjectCreateInfo,
326 UniquePtr<SyncObject>&& oldSyncObject)
328 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
330 return NewObject<EGL::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
334 return NewObject<GLES::SyncObject>(syncObjectCreateInfo, *this, std::move(oldSyncObject));
338 TextureProperties EglGraphicsController::GetTextureProperties(const Texture& texture)
340 const GLES::Texture* glesTexture = static_cast<const GLES::Texture*>(&texture);
341 auto createInfo = glesTexture->GetCreateInfo();
343 TextureProperties properties{};
344 properties.format = createInfo.format;
345 properties.compressed = glesTexture->IsCompressed();
346 properties.extent2D = createInfo.size;
347 properties.nativeHandle = glesTexture->GetGLTexture();
348 // TODO: Skip format1, emulated, packed, directWriteAccessEnabled of TextureProperties for now
353 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
355 return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
358 void EglGraphicsController::CreateSurfaceContext(Dali::RenderSurfaceInterface* surface)
360 std::unique_ptr<GLES::Context> context = std::make_unique<GLES::Context>(*this);
361 mSurfaceContexts.push_back(std::move(std::make_pair(surface, std::move(context))));
364 void EglGraphicsController::DeleteSurfaceContext(Dali::RenderSurfaceInterface* surface)
366 mSurfaceContexts.erase(std::remove_if(
367 mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return surface == iter.first; }),
368 mSurfaceContexts.end());
371 void EglGraphicsController::ActivateResourceContext()
373 mCurrentContext = mContext.get();
374 mCurrentContext->GlContextCreated();
377 auto eglGraphics = dynamic_cast<Dali::Internal::Adaptor::EglGraphics*>(mGraphics);
380 mSharedContext = eglGraphics->GetEglImplementation().GetContext();
385 void EglGraphicsController::ActivateSurfaceContext(Dali::RenderSurfaceInterface* surface)
387 if(surface && mGraphics->IsResourceContextSupported())
389 auto iter = std::find_if(mSurfaceContexts.begin(), mSurfaceContexts.end(), [surface](SurfaceContextPair& iter) { return (iter.first == surface); });
391 if(iter != mSurfaceContexts.end())
393 mCurrentContext = iter->second.get();
394 mCurrentContext->GlContextCreated();
399 void EglGraphicsController::AddTexture(GLES::Texture& texture)
401 // Assuming we are on the correct context
402 mCreateTextureQueue.push(&texture);
405 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
407 // Assuming we are on the correct context
408 mCreateBufferQueue.push(&buffer);
411 void EglGraphicsController::AddFramebuffer(GLES::Framebuffer& framebuffer)
413 // Assuming we are on the correct context
414 mCreateFramebufferQueue.push(&framebuffer);
417 void EglGraphicsController::ProcessDiscardQueues()
420 ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
423 ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
425 // Process Framebuffers
426 ProcessDiscardQueue<GLES::Framebuffer>(mDiscardFramebufferQueue);
428 // Process RenderPass
429 ProcessDiscardQueue<GLES::RenderPass>(mDiscardRenderPassQueue);
431 // Process RenderTarget
432 ProcessDiscardQueue<GLES::RenderTarget>(mDiscardRenderTargetQueue);
435 ProcessDiscardQueue(mDiscardPipelineQueue);
438 ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
441 ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
444 ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
446 // Process command buffers
447 ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
450 void EglGraphicsController::ProcessCreateQueues()
453 ProcessCreateQueue(mCreateTextureQueue);
456 ProcessCreateQueue(mCreateBufferQueue);
458 // Process framebuffers
459 ProcessCreateQueue(mCreateFramebufferQueue);
462 void EglGraphicsController::ProcessCommandBuffer(const GLES::CommandBuffer& commandBuffer)
465 const auto commands = commandBuffer.GetCommands(count);
466 for(auto i = 0u; i < count; ++i)
468 auto& cmd = commands[i];
472 case GLES::CommandType::FLUSH:
474 // Nothing to do here
477 case GLES::CommandType::BIND_TEXTURES:
479 mCurrentContext->BindTextures(cmd.bindTextures.textureBindings.Ptr(), cmd.bindTextures.textureBindingsCount);
482 case GLES::CommandType::BIND_VERTEX_BUFFERS:
484 auto bindings = cmd.bindVertexBuffers.vertexBufferBindings.Ptr();
485 mCurrentContext->BindVertexBuffers(bindings, cmd.bindVertexBuffers.vertexBufferBindingsCount);
488 case GLES::CommandType::BIND_UNIFORM_BUFFER:
490 auto& bindings = cmd.bindUniformBuffers;
491 mCurrentContext->BindUniformBuffers(bindings.uniformBufferBindingsCount ? bindings.uniformBufferBindings.Ptr() : nullptr, bindings.uniformBufferBindingsCount, bindings.standaloneUniformsBufferBinding);
494 case GLES::CommandType::BIND_INDEX_BUFFER:
496 mCurrentContext->BindIndexBuffer(cmd.bindIndexBuffer);
499 case GLES::CommandType::BIND_SAMPLERS:
503 case GLES::CommandType::BIND_PIPELINE:
505 auto pipeline = static_cast<const GLES::Pipeline*>(cmd.bindPipeline.pipeline);
506 mCurrentContext->BindPipeline(pipeline);
509 case GLES::CommandType::DRAW:
511 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
514 case GLES::CommandType::DRAW_INDEXED:
516 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
519 case GLES::CommandType::DRAW_INDEXED_INDIRECT:
521 mCurrentContext->Flush(false, cmd.draw, mTextureDependencyChecker);
524 case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
526 mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
529 case GLES::CommandType::SET_SCISSOR_TEST:
531 mCurrentContext->SetScissorTestEnabled(cmd.scissorTest.enable);
534 case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
536 mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
540 case GLES::CommandType::SET_COLOR_MASK:
542 mCurrentContext->ColorMask(cmd.colorMask.enabled);
545 case GLES::CommandType::CLEAR_STENCIL_BUFFER:
547 mCurrentContext->ClearStencilBuffer();
550 case GLES::CommandType::CLEAR_DEPTH_BUFFER:
552 mCurrentContext->ClearDepthBuffer();
556 case GLES::CommandType::SET_STENCIL_TEST_ENABLE:
558 mCurrentContext->SetStencilTestEnable(cmd.stencilTest.enabled);
562 case GLES::CommandType::SET_STENCIL_FUNC:
564 mCurrentContext->StencilFunc(cmd.stencilFunc.compareOp,
565 cmd.stencilFunc.reference,
566 cmd.stencilFunc.compareMask);
570 case GLES::CommandType::SET_STENCIL_WRITE_MASK:
572 mCurrentContext->StencilMask(cmd.stencilWriteMask.mask);
576 case GLES::CommandType::SET_STENCIL_OP:
578 mCurrentContext->StencilOp(cmd.stencilOp.failOp,
579 cmd.stencilOp.depthFailOp,
580 cmd.stencilOp.passOp);
584 case GLES::CommandType::SET_DEPTH_COMPARE_OP:
586 mCurrentContext->SetDepthCompareOp(cmd.depth.compareOp);
589 case GLES::CommandType::SET_DEPTH_TEST_ENABLE:
591 mCurrentContext->SetDepthTestEnable(cmd.depth.testEnabled);
594 case GLES::CommandType::SET_DEPTH_WRITE_ENABLE:
596 mCurrentContext->SetDepthWriteEnable(cmd.depth.writeEnabled);
600 case GLES::CommandType::BEGIN_RENDERPASS:
602 auto& renderTarget = *cmd.beginRenderPass.renderTarget;
603 const auto& targetInfo = renderTarget.GetCreateInfo();
605 if(targetInfo.surface)
607 // switch to surface context
608 mGraphics->ActivateSurfaceContext(static_cast<Dali::RenderSurfaceInterface*>(targetInfo.surface));
610 else if(targetInfo.framebuffer)
612 // switch to resource context
613 mGraphics->ActivateResourceContext();
616 mCurrentContext->BeginRenderPass(cmd.beginRenderPass);
620 case GLES::CommandType::END_RENDERPASS:
622 mCurrentContext->EndRenderPass(mTextureDependencyChecker);
624 // This sync object is to enable cpu to wait for rendering to complete, not gpu.
625 // It's only needed for reading the framebuffer texture in the client.
626 auto syncObject = const_cast<GLES::SyncObject*>(static_cast<const GLES::SyncObject*>(cmd.endRenderPass.syncObject));
629 syncObject->InitializeResource();
633 case GLES::CommandType::PRESENT_RENDER_TARGET:
635 ResolvePresentRenderTarget(cmd.presentRenderTarget.targetToPresent);
637 // The command buffer will be pushed into the queue of presentation command buffers
638 // for further reuse.
639 if(commandBuffer.GetCreateInfo().fixedCapacity == 1)
641 mPresentationCommandBuffers.push(&commandBuffer);
645 case GLES::CommandType::EXECUTE_COMMAND_BUFFERS:
647 // Process secondary command buffers
648 // todo: check validity of the secondaries
649 // there are operations which are illigal to be done
650 // within secondaries.
651 auto buffers = cmd.executeCommandBuffers.buffers.Ptr();
652 for(auto j = 0u; j < cmd.executeCommandBuffers.buffersCount; ++j)
654 auto& buf = buffers[j];
655 ProcessCommandBuffer(*static_cast<const GLES::CommandBuffer*>(buf));
659 case GLES::CommandType::DRAW_NATIVE:
661 auto* info = &cmd.drawNative.drawNativeInfo;
663 mCurrentContext->PrepareForNativeRendering();
665 if(info->glesNativeInfo.eglSharedContextStoragePointer)
667 auto* anyContext = reinterpret_cast<std::any*>(info->glesNativeInfo.eglSharedContextStoragePointer);
668 *anyContext = mSharedContext;
671 CallbackBase::ExecuteReturn<bool>(*info->callback, info->userData);
673 mCurrentContext->RestoreFromNativeRendering();
680 void EglGraphicsController::ProcessCommandQueues()
684 while(!mCommandQueue.empty())
686 auto cmdBuf = mCommandQueue.front();
688 DUMP_FRAME_COMMAND_BUFFER(cmdBuf);
689 ProcessCommandBuffer(*cmdBuf);
695 void EglGraphicsController::ProcessTextureUpdateQueue()
697 while(!mTextureUpdateRequests.empty())
699 TextureUpdateRequest& request = mTextureUpdateRequests.front();
701 auto& info = request.first;
702 auto& source = request.second;
704 switch(source.sourceType)
706 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
707 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
709 // GPU memory must be already allocated.
711 // Check if it needs conversion
712 auto* texture = static_cast<GLES::Texture*>(info.dstTexture);
713 const auto& createInfo = texture->GetCreateInfo();
714 auto srcFormat = GLES::GLTextureFormatType(info.srcFormat).format;
715 auto srcType = GLES::GLTextureFormatType(info.srcFormat).type;
716 auto destInternalFormat = GLES::GLTextureFormatType(createInfo.format).internalFormat;
717 auto destFormat = GLES::GLTextureFormatType(createInfo.format).format;
719 // From render-texture.cpp
720 const bool isSubImage(info.dstOffset2D.x != 0 || info.dstOffset2D.y != 0 ||
721 info.srcExtent2D.width != (createInfo.size.width / (1 << info.level)) ||
722 info.srcExtent2D.height != (createInfo.size.height / (1 << info.level)));
724 uint8_t* sourceBuffer;
725 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
727 sourceBuffer = reinterpret_cast<uint8_t*>(source.memorySource.memory);
731 // Get buffer of PixelData
732 Dali::Integration::PixelDataBuffer pixelBufferData = Dali::Integration::GetPixelDataBuffer(source.pixelDataSource.pixelData);
734 sourceBuffer = pixelBufferData.buffer + info.srcOffset;
737 auto sourceStride = info.srcStride;
738 std::vector<uint8_t> tempBuffer;
740 if(mGlAbstraction->TextureRequiresConverting(srcFormat, destFormat, isSubImage))
742 // Convert RGB to RGBA if necessary.
743 if(texture->TryConvertPixelData(sourceBuffer, info.srcFormat, createInfo.format, info.srcSize, info.srcStride, info.srcExtent2D.width, info.srcExtent2D.height, tempBuffer))
745 sourceBuffer = &tempBuffer[0];
746 sourceStride = 0u; // Converted buffer compacted. make stride as 0.
747 srcFormat = destFormat;
748 srcType = GLES::GLTextureFormatType(createInfo.format).type;
752 // Calculate the maximum mipmap level for the texture
753 texture->SetMaxMipMapLevel(std::max(texture->GetMaxMipMapLevel(), info.level));
755 GLenum bindTarget{GL_TEXTURE_2D};
756 GLenum target{GL_TEXTURE_2D};
758 if(createInfo.textureType == Graphics::TextureType::TEXTURE_CUBEMAP)
760 bindTarget = GL_TEXTURE_CUBE_MAP;
761 target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + info.layer;
764 mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
765 mGlAbstraction->PixelStorei(GL_UNPACK_ROW_LENGTH, sourceStride);
767 mCurrentContext->BindTexture(bindTarget, texture->GetTextureTypeId(), texture->GetGLTexture());
771 if(!texture->IsCompressed())
773 mGlAbstraction->TexImage2D(target,
776 info.srcExtent2D.width,
777 info.srcExtent2D.height,
785 mGlAbstraction->CompressedTexImage2D(target,
788 info.srcExtent2D.width,
789 info.srcExtent2D.height,
797 if(!texture->IsCompressed())
799 mGlAbstraction->TexSubImage2D(target,
803 info.srcExtent2D.width,
804 info.srcExtent2D.height,
811 mGlAbstraction->CompressedTexSubImage2D(target,
815 info.srcExtent2D.width,
816 info.srcExtent2D.height,
823 if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
825 // free staging memory
826 free(source.memorySource.memory);
832 // TODO: other sources
837 mTextureUpdateRequests.pop();
841 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>& updateInfoList,
842 const std::vector<TextureUpdateSourceInfo>& sourceList)
845 for(auto& info : updateInfoList)
847 mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
848 auto& pair = mTextureUpdateRequests.back();
849 switch(pair.second.sourceType)
851 case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
853 auto& info = pair.first;
854 auto& source = pair.second;
856 // allocate staging memory and copy the data
857 // TODO: using PBO with GLES3, this is just naive
860 uint8_t* stagingBuffer = reinterpret_cast<uint8_t*>(malloc(info.srcSize));
862 uint8_t* srcMemory = &reinterpret_cast<uint8_t*>(source.memorySource.memory)[info.srcOffset];
864 std::copy(srcMemory, srcMemory + info.srcSize, stagingBuffer);
866 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
868 // store staging buffer
869 source.memorySource.memory = stagingBuffer;
872 case Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA:
874 // Increase CPU memory usage since ownership of PixelData is now on mTextureUpdateRequests.
875 mTextureUploadTotalCPUMemoryUsed += info.srcSize;
878 case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
880 // TODO, with PBO support
883 case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
885 // TODO texture 2 texture in-GPU copy
891 // If upload buffer exceeds maximum size, flush.
892 if(mTextureUploadTotalCPUMemoryUsed > TEXTURE_UPLOAD_MAX_BUFER_SIZE_MB * 1024 * 1024)
895 mTextureUploadTotalCPUMemoryUsed = 0;
899 void EglGraphicsController::ProcessTextureMipmapGenerationQueue()
901 while(!mTextureMipmapGenerationRequests.empty())
903 auto* texture = mTextureMipmapGenerationRequests.front();
905 mCurrentContext->BindTexture(texture->GetGlTarget(), texture->GetTextureTypeId(), texture->GetGLTexture());
906 mCurrentContext->GenerateMipmap(texture->GetGlTarget());
908 mTextureMipmapGenerationRequests.pop();
912 void EglGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
914 mTextureMipmapGenerationRequests.push(static_cast<const GLES::Texture*>(&texture));
917 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
919 mGraphics->ActivateResourceContext();
921 // Mapping buffer requires the object to be created NOW
922 // Workaround - flush now, otherwise there will be given a staging buffer
923 // in case when the buffer is not there yet
924 ProcessCreateQueues();
926 if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
928 return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
932 return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
936 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
938 return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
941 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
943 return *mPipelineCache;
946 } // namespace Dali::Graphics