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 "gles-context.h"
19 #include <dali/integration-api/adaptor-framework/render-surface-interface.h>
20 #include <dali/integration-api/debug.h>
21 #include <dali/integration-api/gl-abstraction.h>
22 #include <dali/integration-api/gl-defines.h>
23 #include <dali/internal/graphics/common/graphics-interface.h>
24 #include <dali/public-api/math/math-utils.h>
26 #include "egl-graphics-controller.h"
27 #include "gles-graphics-buffer.h"
28 #include "gles-graphics-pipeline.h"
29 #include "gles-graphics-program.h"
30 #include "gles-graphics-render-pass.h"
31 #include "gles-graphics-render-target.h"
32 #include "gles-texture-dependency-checker.h"
35 #include <EGL/eglext.h>
37 #include <unordered_map>
39 namespace Dali::Graphics::GLES
43 explicit Impl(EglGraphicsController& controller)
44 : mController(controller)
51 * Binds (and creates) VAO
53 * VAO is fixed per program so it has to be created only once assuming
54 * that VertexInputState has been set correctly for the pipeline.
57 void BindProgramVAO(const GLES::ProgramImpl* program, const VertexInputState& vertexInputState)
59 // Calculate attributes location hash unordered.
61 for(const auto& attr : vertexInputState.attributes)
63 hash ^= std::hash<uint32_t>{}(attr.location);
66 auto& gl = *mController.GetGL();
67 auto iter = mProgramVAOMap.find(program);
68 if(iter != mProgramVAOMap.end())
70 auto attributeIter = iter->second.find(hash);
71 if(attributeIter != iter->second.end())
73 if(mProgramVAOCurrentState != attributeIter->second)
75 mProgramVAOCurrentState = attributeIter->second;
76 gl.BindVertexArray(attributeIter->second);
78 // Binding VAO seems to reset the index buffer binding so the cache must be reset
79 mGlStateCache.mBoundElementArrayBufferId = 0;
86 gl.GenVertexArrays(1, &vao);
87 gl.BindVertexArray(vao);
89 // Binding VAO seems to reset the index buffer binding so the cache must be reset
90 mGlStateCache.mBoundElementArrayBufferId = 0;
92 mProgramVAOMap[program][hash] = vao;
93 for(const auto& attr : vertexInputState.attributes)
95 gl.EnableVertexAttribArray(attr.location);
98 mProgramVAOCurrentState = vao;
102 * Sets the initial GL state.
104 void InitializeGlState()
106 auto& gl = *mController.GetGL();
108 mGlStateCache.mClearColorSet = false;
109 mGlStateCache.mColorMask = true;
110 mGlStateCache.mStencilMask = 0xFF;
111 mGlStateCache.mBlendEnabled = false;
112 mGlStateCache.mDepthBufferEnabled = false;
113 mGlStateCache.mDepthMaskEnabled = false;
114 mGlStateCache.mScissorTestEnabled = false;
115 mGlStateCache.mStencilBufferEnabled = false;
117 gl.Disable(GL_DITHER);
119 mGlStateCache.mBoundArrayBufferId = 0;
120 mGlStateCache.mBoundElementArrayBufferId = 0;
121 mGlStateCache.mActiveTextureUnit = 0;
123 mGlStateCache.mBlendFuncSeparateSrcRGB = BlendFactor::ONE;
124 mGlStateCache.mBlendFuncSeparateDstRGB = BlendFactor::ZERO;
125 mGlStateCache.mBlendFuncSeparateSrcAlpha = BlendFactor::ONE;
126 mGlStateCache.mBlendFuncSeparateDstAlpha = BlendFactor::ZERO;
128 // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
129 mGlStateCache.mBlendEquationSeparateModeRGB = BlendOp::ADD;
130 mGlStateCache.mBlendEquationSeparateModeAlpha = BlendOp::ADD;
132 mGlStateCache.mCullFaceMode = CullMode::NONE; //By default cullface is disabled, front face is set to CCW and cull face is set to back
134 //Initialze vertex attribute cache
135 memset(&mGlStateCache.mVertexAttributeCachedState, 0, sizeof(mGlStateCache.mVertexAttributeCachedState));
136 memset(&mGlStateCache.mVertexAttributeCurrentState, 0, sizeof(mGlStateCache.mVertexAttributeCurrentState));
138 //Initialize bound 2d texture cache
139 memset(&mGlStateCache.mBoundTextureId, 0, sizeof(mGlStateCache.mBoundTextureId));
141 mGlStateCache.mFrameBufferStateCache.Reset();
144 gl.GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextures);
145 DALI_LOG_RELEASE_INFO("GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: %d\n", maxTextures);
149 * Flushes vertex attribute location changes to the driver
151 void FlushVertexAttributeLocations()
153 auto& gl = *mController.GetGL();
155 for(unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i)
157 // see if the cached state is different to the actual state
158 if(mGlStateCache.mVertexAttributeCurrentState[i] != mGlStateCache.mVertexAttributeCachedState[i])
160 // it's different so make the change to the driver and update the cached state
161 mGlStateCache.mVertexAttributeCurrentState[i] = mGlStateCache.mVertexAttributeCachedState[i];
163 if(mGlStateCache.mVertexAttributeCurrentState[i])
165 gl.EnableVertexAttribArray(i);
169 gl.DisableVertexAttribArray(i);
176 * Either enables or disables a vertex attribute location in the cache
177 * The cahnges won't take affect until FlushVertexAttributeLocations is called
178 * @param location attribute location
179 * @param state attribute state
181 void SetVertexAttributeLocation(unsigned int location, bool state)
183 auto& gl = *mController.GetGL();
185 if(location >= MAX_ATTRIBUTE_CACHE_SIZE)
187 // not cached, make the gl call through context
190 gl.EnableVertexAttribArray(location);
194 gl.DisableVertexAttribArray(location);
199 // set the cached state, it will be set at the next draw call
200 // if it's different from the current driver state
201 mGlStateCache.mVertexAttributeCachedState[location] = state;
205 EglGraphicsController& mController;
207 const GLES::PipelineImpl* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
208 const GLES::PipelineImpl* mNewPipeline{nullptr}; ///< New pipeline to be set on flush
210 std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
211 std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
212 GLES::IndexBufferBindingDescriptor mCurrentIndexBufferBinding{};
214 struct VertexBufferBinding
216 GLES::Buffer* buffer{nullptr};
220 // Currently bound buffers
221 std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
223 // Currently bound UBOs (check if it's needed per program!)
224 std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
225 UniformBufferBindingDescriptor mCurrentStandaloneUBOBinding{};
227 // Current render pass and render target
228 const GLES::RenderTarget* mCurrentRenderTarget{nullptr};
229 const GLES::RenderPass* mCurrentRenderPass{nullptr};
231 // Each context must have own VAOs as they cannot be shared
232 std::unordered_map<const GLES::ProgramImpl*, std::map<std::size_t, uint32_t>> mProgramVAOMap; ///< GL program-VAO map
233 uint32_t mProgramVAOCurrentState{0u}; ///< Currently bound VAO
234 GLStateCache mGlStateCache{}; ///< GL status cache
236 bool mGlContextCreated{false}; ///< True if the OpenGL context has been created
237 bool mVertexBuffersChanged{true}; ///< True if BindVertexBuffers changed any buffer bindings
239 EGLContext mNativeDrawContext{0u}; ///< Native rendering EGL context compatible with window context
241 EGLSurface mCacheDrawReadSurface{0u}; ///< cached 'read' surface
242 EGLSurface mCacheDrawWriteSurface{0u}; ///< cached 'write' surface
243 EGLContext mCacheEGLGraphicsContext{0u}; ///< cached window context
246 Context::Context(EglGraphicsController& controller)
248 mImpl = std::make_unique<Impl>(controller);
253 // Destroy native rendering context if one exists
254 if(mImpl->mNativeDrawContext)
256 eglDestroyContext(eglGetCurrentDisplay(), mImpl->mNativeDrawContext);
257 mImpl->mNativeDrawContext = EGL_NO_CONTEXT;
261 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall, GLES::TextureDependencyChecker& dependencyChecker)
263 auto& gl = *mImpl->mController.GetGL();
265 static const bool hasGLES3(mImpl->mController.GetGLESVersion() >= GLESVersion::GLES_30);
267 // early out if neither current nor new pipelines are set
268 // this behaviour may be valid so no assert
269 if(!mImpl->mCurrentPipeline && !mImpl->mNewPipeline)
274 // Execute states if pipeline is changed
275 const auto currentProgram = mImpl->mCurrentPipeline ? static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program) : nullptr;
277 // case when new pipeline has been set
278 const GLES::Program* newProgram = nullptr;
280 if(mImpl->mNewPipeline)
282 newProgram = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
285 if(!currentProgram && !newProgram)
287 // Early out if we have no program for this pipeline.
288 DALI_LOG_ERROR("No program defined for pipeline\n");
292 // If this draw uses a different pipeline _AND_ the pipeline has a different GL Program,
293 // Then bind the new program. Ensure vertex atrributes are set.
295 bool programChanged = false;
296 if(mImpl->mNewPipeline && mImpl->mCurrentPipeline != mImpl->mNewPipeline)
298 if(!currentProgram || currentProgram->GetImplementation()->GetGlProgram() != newProgram->GetImplementation()->GetGlProgram())
300 mImpl->mNewPipeline->Bind(newProgram->GetImplementation()->GetGlProgram());
301 programChanged = true;
307 // Resolve rasterization state
308 ResolveRasterizationState();
311 // Resolve uniform buffers
312 ResolveUniformBuffers();
315 // Map binding# to sampler location
316 const auto& reflection = !newProgram ? currentProgram->GetReflection() : newProgram->GetReflection();
317 const auto& samplers = reflection.GetSamplers();
319 uint32_t currentSampler = 0;
320 uint32_t currentElement = 0;
322 // @warning Assume that binding.binding is strictly linear in the same order as mCurrentTextureBindings
323 // elements. This avoids having to sort the bindings.
324 for(const auto& binding : mImpl->mCurrentTextureBindings)
326 auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
328 // Texture may not have been initialized yet...(tbm_surface timing issue?)
329 if(!texture->GetGLTexture())
331 texture->InitializeResource();
334 // Warning, this may cause glWaitSync to occur on the GPU.
335 dependencyChecker.CheckNeedsSync(this, texture);
336 texture->Bind(binding);
341 // @warning Assume that location of array elements is sequential.
342 // @warning GL does not guarantee this, but in practice, it is.
343 gl.Uniform1i(samplers[currentSampler].location + currentElement,
344 samplers[currentSampler].offset + currentElement);
346 if(currentElement >= samplers[currentSampler].elementCount)
352 if(currentSampler >= samplers.size())
354 // Don't bind more textures than there are active samplers.
359 const auto& pipelineState = mImpl->mNewPipeline ? mImpl->mNewPipeline->GetCreateInfo() : mImpl->mCurrentPipeline->GetCreateInfo();
360 const auto& vertexInputState = pipelineState.vertexInputState;
362 // for each attribute bind vertices, unless the pipeline+buffer is the same
363 if(programChanged || mImpl->mVertexBuffersChanged)
367 mImpl->BindProgramVAO(static_cast<const GLES::Program*>(pipelineState.programState->program)->GetImplementation(), *vertexInputState);
370 for(const auto& attr : vertexInputState->attributes)
375 mImpl->SetVertexAttributeLocation(attr.location, true);
378 const auto& bufferSlot = mImpl->mCurrentVertexBufferBindings[attr.binding];
379 const auto& bufferBinding = vertexInputState->bufferBindings[attr.binding];
381 auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
383 BindBuffer(GL_ARRAY_BUFFER, glesBuffer); // Cached
385 if(attr.format == VertexInputFormat::FLOAT ||
386 attr.format == VertexInputFormat::FVECTOR2 ||
387 attr.format == VertexInputFormat::FVECTOR3 ||
388 attr.format == VertexInputFormat::FVECTOR4)
390 gl.VertexAttribPointer(attr.location, // Not cached...
391 GLVertexFormat(attr.format).size,
392 GLVertexFormat(attr.format).format,
394 bufferBinding.stride,
395 reinterpret_cast<void*>(attr.offset));
399 gl.VertexAttribIPointer(attr.location,
400 GLVertexFormat(attr.format).size,
401 GLVertexFormat(attr.format).format,
402 bufferBinding.stride,
403 reinterpret_cast<void*>(attr.offset));
406 switch(bufferBinding.inputRate)
408 case Graphics::VertexInputRate::PER_VERTEX:
410 gl.VertexAttribDivisor(attr.location, 0);
413 case Graphics::VertexInputRate::PER_INSTANCE:
415 //@todo Get actual instance rate...
416 gl.VertexAttribDivisor(attr.location, 1);
424 const auto& ia = pipelineState.inputAssemblyState;
427 switch(drawCall.type)
429 case DrawCallDescriptor::Type::DRAW:
431 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
432 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
433 mImpl->mGlStateCache.StencilBufferWriteEnabled());
434 // For GLES3+ we use VAO, for GLES2 internal cache
437 mImpl->FlushVertexAttributeLocations();
440 if(drawCall.draw.instanceCount == 0)
442 gl.DrawArrays(GLESTopology(ia->topology),
443 drawCall.draw.firstVertex,
444 drawCall.draw.vertexCount);
448 gl.DrawArraysInstanced(GLESTopology(ia->topology),
449 drawCall.draw.firstVertex,
450 drawCall.draw.vertexCount,
451 drawCall.draw.instanceCount);
455 case DrawCallDescriptor::Type::DRAW_INDEXED:
457 const auto& binding = mImpl->mCurrentIndexBufferBinding;
458 BindBuffer(GL_ELEMENT_ARRAY_BUFFER, binding.buffer->GetGLBuffer());
460 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
461 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
462 mImpl->mGlStateCache.StencilBufferWriteEnabled());
464 // For GLES3+ we use VAO, for GLES2 internal cache
467 mImpl->FlushVertexAttributeLocations();
470 auto indexBufferFormat = GLIndexFormat(binding.format).format;
471 if(drawCall.drawIndexed.instanceCount == 0)
473 gl.DrawElements(GLESTopology(ia->topology),
474 drawCall.drawIndexed.indexCount,
476 reinterpret_cast<void*>(binding.offset));
480 gl.DrawElementsInstanced(GLESTopology(ia->topology),
481 drawCall.drawIndexed.indexCount,
483 reinterpret_cast<void*>(binding.offset),
484 drawCall.drawIndexed.instanceCount);
488 case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
497 if(mImpl->mNewPipeline)
499 mImpl->mCurrentPipeline = mImpl->mNewPipeline;
500 mImpl->mNewPipeline = nullptr;
504 void Context::BindTextures(const Graphics::TextureBinding* bindings, uint32_t count)
506 // for each texture allocate slot
507 for(auto i = 0u; i < count; ++i)
509 auto& binding = bindings[i];
511 // Resize binding array if needed
512 if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
514 mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
516 // Store the binding details
517 mImpl->mCurrentTextureBindings[binding.binding] = binding;
521 void Context::BindVertexBuffers(const GLES::VertexBufferBindingDescriptor* bindings, uint32_t count)
523 if(count > mImpl->mCurrentVertexBufferBindings.size())
525 mImpl->mCurrentVertexBufferBindings.resize(count);
527 // Copy only set slots
528 mImpl->mVertexBuffersChanged = false;
529 auto toIter = mImpl->mCurrentVertexBufferBindings.begin();
530 for(auto fromIter = bindings, end = bindings + count; fromIter != end; ++fromIter)
532 if(fromIter->buffer != nullptr)
534 if(toIter->buffer != fromIter->buffer || toIter->offset != fromIter->offset)
536 mImpl->mVertexBuffersChanged = true;
538 *toIter++ = *fromIter;
543 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
545 mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
548 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
550 DALI_ASSERT_ALWAYS(newPipeline && "Invalid pipeline");
551 mImpl->mNewPipeline = &newPipeline->GetPipeline();
554 void Context::BindUniformBuffers(const UniformBufferBindingDescriptor* uboBindings,
556 const UniformBufferBindingDescriptor& standaloneBindings)
558 if(standaloneBindings.buffer)
560 mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
563 if(uboCount >= mImpl->mCurrentUBOBindings.size())
565 mImpl->mCurrentUBOBindings.resize(uboCount + 1);
568 auto it = uboBindings;
569 for(auto i = 0u; i < uboCount; ++i)
573 mImpl->mCurrentUBOBindings[i] = *it;
578 void Context::ResolveBlendState()
580 const auto& currentBlendState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().colorBlendState : nullptr;
581 const auto& newBlendState = mImpl->mNewPipeline->GetCreateInfo().colorBlendState;
583 // TODO: prevent leaking the state
589 auto& gl = *mImpl->mController.GetGL();
591 if(!currentBlendState || currentBlendState->blendEnable != newBlendState->blendEnable)
593 if(newBlendState->blendEnable != mImpl->mGlStateCache.mBlendEnabled)
595 mImpl->mGlStateCache.mBlendEnabled = newBlendState->blendEnable;
596 newBlendState->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
600 if(!newBlendState->blendEnable)
605 BlendFactor newSrcRGB(newBlendState->srcColorBlendFactor);
606 BlendFactor newDstRGB(newBlendState->dstColorBlendFactor);
607 BlendFactor newSrcAlpha(newBlendState->srcAlphaBlendFactor);
608 BlendFactor newDstAlpha(newBlendState->dstAlphaBlendFactor);
610 if(!currentBlendState ||
611 currentBlendState->srcColorBlendFactor != newSrcRGB ||
612 currentBlendState->dstColorBlendFactor != newDstRGB ||
613 currentBlendState->srcAlphaBlendFactor != newSrcAlpha ||
614 currentBlendState->dstAlphaBlendFactor != newDstAlpha)
616 if((mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB != newSrcRGB) ||
617 (mImpl->mGlStateCache.mBlendFuncSeparateDstRGB != newDstRGB) ||
618 (mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha != newSrcAlpha) ||
619 (mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha != newDstAlpha))
621 mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB = newSrcRGB;
622 mImpl->mGlStateCache.mBlendFuncSeparateDstRGB = newDstRGB;
623 mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha = newSrcAlpha;
624 mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha = newDstAlpha;
626 if(newSrcRGB == newSrcAlpha && newDstRGB == newDstAlpha)
628 gl.BlendFunc(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB));
632 gl.BlendFuncSeparate(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB), GLBlendFunc(newSrcAlpha), GLBlendFunc(newDstAlpha));
637 if(!currentBlendState ||
638 currentBlendState->colorBlendOp != newBlendState->colorBlendOp ||
639 currentBlendState->alphaBlendOp != newBlendState->alphaBlendOp)
641 if(mImpl->mGlStateCache.mBlendEquationSeparateModeRGB != newBlendState->colorBlendOp ||
642 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha != newBlendState->alphaBlendOp)
644 mImpl->mGlStateCache.mBlendEquationSeparateModeRGB = newBlendState->colorBlendOp;
645 mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha = newBlendState->alphaBlendOp;
647 if(newBlendState->colorBlendOp == newBlendState->alphaBlendOp)
649 gl.BlendEquation(GLBlendOp(newBlendState->colorBlendOp));
650 if(newBlendState->colorBlendOp >= Graphics::ADVANCED_BLEND_OPTIONS_START)
657 gl.BlendEquationSeparate(GLBlendOp(newBlendState->colorBlendOp), GLBlendOp(newBlendState->alphaBlendOp));
663 void Context::ResolveRasterizationState()
665 const auto& currentRasterizationState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().rasterizationState : nullptr;
666 const auto& newRasterizationState = mImpl->mNewPipeline->GetCreateInfo().rasterizationState;
668 // TODO: prevent leaking the state
669 if(!newRasterizationState)
674 auto& gl = *mImpl->mController.GetGL();
676 if(!currentRasterizationState ||
677 currentRasterizationState->cullMode != newRasterizationState->cullMode)
679 if(mImpl->mGlStateCache.mCullFaceMode != newRasterizationState->cullMode)
681 mImpl->mGlStateCache.mCullFaceMode = newRasterizationState->cullMode;
682 if(newRasterizationState->cullMode == CullMode::NONE)
684 gl.Disable(GL_CULL_FACE);
688 gl.Enable(GL_CULL_FACE);
689 gl.CullFace(GLCullMode(newRasterizationState->cullMode));
693 // TODO: implement polygon mode (fill, line, points)
694 // seems like we don't support it (no glPolygonMode())
697 void Context::ResolveUniformBuffers()
699 // Resolve standalone uniforms if we have binding
700 if(mImpl->mCurrentStandaloneUBOBinding.buffer)
702 ResolveStandaloneUniforms();
706 void Context::ResolveStandaloneUniforms()
708 // Find reflection for program
709 const GLES::Program* program{nullptr};
711 if(mImpl->mNewPipeline)
713 program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
715 else if(mImpl->mCurrentPipeline)
717 program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
722 const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
723 // Update program uniforms
724 program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
728 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
730 auto& renderPass = *renderPassBegin.renderPass;
731 auto& renderTarget = *renderPassBegin.renderTarget;
733 const auto& targetInfo = renderTarget.GetCreateInfo();
735 auto& gl = *mImpl->mController.GetGL();
737 if(targetInfo.surface)
740 BindFrameBuffer(GL_FRAMEBUFFER, 0);
742 else if(targetInfo.framebuffer)
744 // bind framebuffer and swap.
745 auto framebuffer = renderTarget.GetFramebuffer();
749 // clear (ideally cache the setup)
751 // In GL we assume that the last attachment is depth/stencil (we may need
752 // to cache extra information inside GLES RenderTarget if we want to be
753 // more specific in case of MRT)
755 const auto& attachments = *renderPass.GetCreateInfo().attachments;
756 const auto& color0 = attachments[0];
759 if(color0.loadOp == AttachmentLoadOp::CLEAR)
761 mask |= GL_COLOR_BUFFER_BIT;
764 // Something goes wrong here if Alpha mask is GL_TRUE
767 const auto clearValues = renderPassBegin.clearValues.Ptr();
769 if(!Dali::Equals(mImpl->mGlStateCache.mClearColor.r, clearValues[0].color.r) ||
770 !Dali::Equals(mImpl->mGlStateCache.mClearColor.g, clearValues[0].color.g) ||
771 !Dali::Equals(mImpl->mGlStateCache.mClearColor.b, clearValues[0].color.b) ||
772 !Dali::Equals(mImpl->mGlStateCache.mClearColor.a, clearValues[0].color.a) ||
773 !mImpl->mGlStateCache.mClearColorSet)
775 gl.ClearColor(clearValues[0].color.r,
776 clearValues[0].color.g,
777 clearValues[0].color.b,
778 clearValues[0].color.a);
780 mImpl->mGlStateCache.mClearColorSet = true;
781 mImpl->mGlStateCache.mClearColor = Vector4(clearValues[0].color.r,
782 clearValues[0].color.g,
783 clearValues[0].color.b,
784 clearValues[0].color.a);
788 // check for depth stencil
789 if(attachments.size() > 1)
791 const auto& depthStencil = attachments.back();
792 if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
794 if(!mImpl->mGlStateCache.mDepthMaskEnabled)
796 mImpl->mGlStateCache.mDepthMaskEnabled = true;
799 mask |= GL_DEPTH_BUFFER_BIT;
801 if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
803 if(mImpl->mGlStateCache.mStencilMask != 0xFF)
805 mImpl->mGlStateCache.mStencilMask = 0xFF;
806 gl.StencilMask(0xFF);
808 mask |= GL_STENCIL_BUFFER_BIT;
812 SetScissorTestEnabled(true);
813 gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
814 ClearBuffer(mask, true);
815 SetScissorTestEnabled(false);
817 mImpl->mCurrentRenderPass = &renderPass;
818 mImpl->mCurrentRenderTarget = &renderTarget;
821 void Context::EndRenderPass(GLES::TextureDependencyChecker& dependencyChecker)
823 if(mImpl->mCurrentRenderTarget)
825 GLES::Framebuffer* framebuffer = mImpl->mCurrentRenderTarget->GetFramebuffer();
828 auto& gl = *mImpl->mController.GetGL();
831 /* @todo Full dependency checking would need to store textures in Begin, and create
832 * fence objects here; but we're going to draw all fbos on shared context in serial,
833 * so no real need (yet). Might want to consider ensuring order of render passes,
834 * but that needs doing in the controller, and would need doing before ProcessCommandQueues.
836 * Currently up to the client to create render tasks in the right order.
839 /* Create fence sync objects. Other contexts can then wait on these fences before reading
842 dependencyChecker.AddTextures(this, framebuffer);
847 void Context::ClearState()
849 mImpl->mCurrentTextureBindings.clear();
852 void Context::ColorMask(bool enabled)
854 if(enabled != mImpl->mGlStateCache.mColorMask)
856 mImpl->mGlStateCache.mColorMask = enabled;
858 auto& gl = *mImpl->mController.GetGL();
859 gl.ColorMask(enabled, enabled, enabled, enabled);
863 void Context::ClearStencilBuffer()
865 ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
868 void Context::ClearDepthBuffer()
870 ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
873 void Context::ClearBuffer(uint32_t mask, bool forceClear)
875 mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
878 auto& gl = *mImpl->mController.GetGL();
883 void Context::InvalidateDepthStencilBuffers()
885 auto& gl = *mImpl->mController.GetGL();
887 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
888 gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
891 void Context::SetScissorTestEnabled(bool scissorEnabled)
893 if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
895 mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
897 auto& gl = *mImpl->mController.GetGL();
900 gl.Enable(GL_SCISSOR_TEST);
904 gl.Disable(GL_SCISSOR_TEST);
909 void Context::SetStencilTestEnable(bool stencilEnable)
911 if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
913 mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
915 auto& gl = *mImpl->mController.GetGL();
918 gl.Enable(GL_STENCIL_TEST);
922 gl.Disable(GL_STENCIL_TEST);
927 void Context::StencilMask(uint32_t writeMask)
929 if(writeMask != mImpl->mGlStateCache.mStencilMask)
931 mImpl->mGlStateCache.mStencilMask = writeMask;
933 auto& gl = *mImpl->mController.GetGL();
934 gl.StencilMask(writeMask);
938 void Context::StencilFunc(Graphics::CompareOp compareOp,
940 uint32_t compareMask)
942 if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
943 reference != mImpl->mGlStateCache.mStencilFuncRef ||
944 compareMask != mImpl->mGlStateCache.mStencilFuncMask)
946 mImpl->mGlStateCache.mStencilFunc = compareOp;
947 mImpl->mGlStateCache.mStencilFuncRef = reference;
948 mImpl->mGlStateCache.mStencilFuncMask = compareMask;
950 auto& gl = *mImpl->mController.GetGL();
951 gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
955 void Context::StencilOp(Graphics::StencilOp failOp,
956 Graphics::StencilOp depthFailOp,
957 Graphics::StencilOp passOp)
959 if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
960 depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
961 passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
963 mImpl->mGlStateCache.mStencilOpFail = failOp;
964 mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
965 mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
967 auto& gl = *mImpl->mController.GetGL();
968 gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
972 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
974 if(compareOp != mImpl->mGlStateCache.mDepthFunction)
976 mImpl->mGlStateCache.mDepthFunction = compareOp;
977 auto& gl = *mImpl->mController.GetGL();
978 gl.DepthFunc(GLCompareOp(compareOp).op);
982 void Context::SetDepthTestEnable(bool depthTestEnable)
984 if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
986 mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
988 auto& gl = *mImpl->mController.GetGL();
991 gl.Enable(GL_DEPTH_TEST);
995 gl.Disable(GL_DEPTH_TEST);
1000 void Context::SetDepthWriteEnable(bool depthWriteEnable)
1002 if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
1004 mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
1006 auto& gl = *mImpl->mController.GetGL();
1007 gl.DepthMask(depthWriteEnable);
1011 void Context::ActiveTexture(uint32_t textureBindingIndex)
1013 if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
1015 mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
1017 auto& gl = *mImpl->mController.GetGL();
1018 gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
1022 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
1024 uint32_t typeId = static_cast<uint32_t>(textureTypeId);
1025 if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
1027 mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
1029 auto& gl = *mImpl->mController.GetGL();
1030 gl.BindTexture(target, textureId);
1034 void Context::GenerateMipmap(GLenum target)
1036 auto& gl = *mImpl->mController.GetGL();
1037 gl.GenerateMipmap(target);
1040 bool Context::BindBuffer(GLenum target, uint32_t bufferId)
1044 case GL_ARRAY_BUFFER:
1046 if(mImpl->mGlStateCache.mBoundArrayBufferId == bufferId)
1050 mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
1053 case GL_ELEMENT_ARRAY_BUFFER:
1055 if(mImpl->mGlStateCache.mBoundElementArrayBufferId == bufferId)
1059 mImpl->mGlStateCache.mBoundElementArrayBufferId = bufferId;
1064 // Cache miss. Bind buffer.
1065 auto& gl = *mImpl->mController.GetGL();
1066 gl.BindBuffer(target, bufferId);
1070 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
1072 mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
1073 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
1074 mImpl->mGlStateCache.StencilBufferWriteEnabled());
1076 auto& gl = *mImpl->mController.GetGL();
1077 gl.DrawBuffers(count, buffers);
1080 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
1082 mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
1084 auto& gl = *mImpl->mController.GetGL();
1085 gl.BindFramebuffer(target, bufferId);
1088 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
1090 auto& gl = *mImpl->mController.GetGL();
1091 gl.GenFramebuffers(count, framebuffers);
1093 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
1096 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
1098 mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
1100 auto& gl = *mImpl->mController.GetGL();
1101 gl.DeleteFramebuffers(count, framebuffers);
1104 GLStateCache& Context::GetGLStateCache()
1106 return mImpl->mGlStateCache;
1109 void Context::GlContextCreated()
1111 if(!mImpl->mGlContextCreated)
1113 mImpl->mGlContextCreated = true;
1115 // Set the initial GL state
1116 mImpl->InitializeGlState();
1120 void Context::GlContextDestroyed()
1122 mImpl->mGlContextCreated = false;
1125 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
1127 // Since the pipeline is deleted, invalidate the cached pipeline.
1128 if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
1130 mImpl->mCurrentPipeline = nullptr;
1133 // Remove cached VAO map
1134 auto* gl = mImpl->mController.GetGL();
1137 const auto* program = pipeline->GetCreateInfo().programState->program;
1140 const auto* programImpl = static_cast<const GLES::Program*>(program)->GetImplementation();
1143 auto iter = mImpl->mProgramVAOMap.find(programImpl);
1144 if(iter != mImpl->mProgramVAOMap.end())
1146 for(auto& attributeHashPair : iter->second)
1148 auto vao = attributeHashPair.second;
1149 gl->DeleteVertexArrays(1, &vao);
1150 if(mImpl->mProgramVAOCurrentState == vao)
1152 mImpl->mProgramVAOCurrentState = 0u;
1155 mImpl->mProgramVAOMap.erase(iter);
1162 void Context::PrepareForNativeRendering()
1164 // this should be pretty much constant
1165 auto display = eglGetCurrentDisplay();
1166 auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
1167 auto readSurface = eglGetCurrentSurface(EGL_READ);
1168 auto context = eglGetCurrentContext();
1170 // push the surface and context data to the impl
1171 // It's needed to restore context
1172 if(!mImpl->mCacheEGLGraphicsContext)
1174 mImpl->mCacheDrawWriteSurface = drawSurface;
1175 mImpl->mCacheDrawReadSurface = readSurface;
1176 mImpl->mCacheEGLGraphicsContext = context;
1179 if(!mImpl->mNativeDrawContext)
1181 EGLint configId{0u};
1182 eglQueryContext(display, mImpl->mController.GetSharedContext(), EGL_CONFIG_ID, &configId);
1184 EGLint configAttribs[3];
1185 configAttribs[0] = EGL_CONFIG_ID;
1186 configAttribs[1] = configId;
1187 configAttribs[2] = EGL_NONE;
1191 if(eglChooseConfig(display, configAttribs, &config, 1, &numConfigs) != EGL_TRUE)
1193 DALI_LOG_ERROR("eglChooseConfig failed!\n");
1197 auto version = int(mImpl->mController.GetGLESVersion());
1199 std::vector<EGLint> attribs;
1200 attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1201 attribs.push_back(version / 10);
1202 attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1203 attribs.push_back(version % 10);
1204 attribs.push_back(EGL_NONE);
1206 mImpl->mNativeDrawContext = eglCreateContext(display, config, mImpl->mController.GetSharedContext(), attribs.data());
1207 if(mImpl->mNativeDrawContext == EGL_NO_CONTEXT)
1209 DALI_LOG_ERROR("eglCreateContext failed!\n");
1214 eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1217 void Context::RestoreFromNativeRendering()
1219 auto display = eglGetCurrentDisplay();
1221 // bring back original context
1222 eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1225 } // namespace Dali::Graphics::GLES