Adding instanced draws
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / gles-context.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
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>
25
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"
33
34 #include <EGL/egl.h>
35 #include <EGL/eglext.h>
36 #include <map>
37 #include <unordered_map>
38
39 namespace Dali::Graphics::GLES
40 {
41 struct Context::Impl
42 {
43   explicit Impl(EglGraphicsController& controller)
44   : mController(controller)
45   {
46   }
47
48   ~Impl() = default;
49
50   /**
51    * Binds (and creates) VAO
52    *
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.
55    *
56    */
57   void BindProgramVAO(const GLES::ProgramImpl* program, const VertexInputState& vertexInputState)
58   {
59     // Calculate attributes location hash unordered.
60     std::size_t hash = 0;
61     for(const auto& attr : vertexInputState.attributes)
62     {
63       hash ^= std::hash<uint32_t>{}(attr.location);
64     }
65
66     auto& gl   = *mController.GetGL();
67     auto  iter = mProgramVAOMap.find(program);
68     if(iter != mProgramVAOMap.end())
69     {
70       auto attributeIter = iter->second.find(hash);
71       if(attributeIter != iter->second.end())
72       {
73         if(mProgramVAOCurrentState != attributeIter->second)
74         {
75           mProgramVAOCurrentState = attributeIter->second;
76           gl.BindVertexArray(attributeIter->second);
77
78           // Binding VAO seems to reset the index buffer binding so the cache must be reset
79           mGlStateCache.mBoundElementArrayBufferId = 0;
80         }
81         return;
82       }
83     }
84
85     uint32_t vao;
86     gl.GenVertexArrays(1, &vao);
87     gl.BindVertexArray(vao);
88
89     // Binding VAO seems to reset the index buffer binding so the cache must be reset
90     mGlStateCache.mBoundElementArrayBufferId = 0;
91
92     mProgramVAOMap[program][hash] = vao;
93     for(const auto& attr : vertexInputState.attributes)
94     {
95       gl.EnableVertexAttribArray(attr.location);
96     }
97
98     mProgramVAOCurrentState = vao;
99   }
100
101   /**
102    * Sets the initial GL state.
103    */
104   void InitializeGlState()
105   {
106     auto& gl = *mController.GetGL();
107
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;
116
117     gl.Disable(GL_DITHER);
118
119     mGlStateCache.mBoundArrayBufferId        = 0;
120     mGlStateCache.mBoundElementArrayBufferId = 0;
121     mGlStateCache.mActiveTextureUnit         = 0;
122
123     mGlStateCache.mBlendFuncSeparateSrcRGB   = BlendFactor::ONE;
124     mGlStateCache.mBlendFuncSeparateDstRGB   = BlendFactor::ZERO;
125     mGlStateCache.mBlendFuncSeparateSrcAlpha = BlendFactor::ONE;
126     mGlStateCache.mBlendFuncSeparateDstAlpha = BlendFactor::ZERO;
127
128     // initial state is GL_FUNC_ADD for both RGB and Alpha blend modes
129     mGlStateCache.mBlendEquationSeparateModeRGB   = BlendOp::ADD;
130     mGlStateCache.mBlendEquationSeparateModeAlpha = BlendOp::ADD;
131
132     mGlStateCache.mCullFaceMode = CullMode::NONE; //By default cullface is disabled, front face is set to CCW and cull face is set to back
133
134     //Initialze vertex attribute cache
135     memset(&mGlStateCache.mVertexAttributeCachedState, 0, sizeof(mGlStateCache.mVertexAttributeCachedState));
136     memset(&mGlStateCache.mVertexAttributeCurrentState, 0, sizeof(mGlStateCache.mVertexAttributeCurrentState));
137
138     //Initialize bound 2d texture cache
139     memset(&mGlStateCache.mBoundTextureId, 0, sizeof(mGlStateCache.mBoundTextureId));
140
141     mGlStateCache.mFrameBufferStateCache.Reset();
142
143     GLint maxTextures;
144     gl.GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextures);
145     DALI_LOG_RELEASE_INFO("GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: %d\n", maxTextures);
146   }
147
148   /**
149    * Flushes vertex attribute location changes to the driver
150    */
151   void FlushVertexAttributeLocations()
152   {
153     auto& gl = *mController.GetGL();
154
155     for(unsigned int i = 0; i < MAX_ATTRIBUTE_CACHE_SIZE; ++i)
156     {
157       // see if the cached state is different to the actual state
158       if(mGlStateCache.mVertexAttributeCurrentState[i] != mGlStateCache.mVertexAttributeCachedState[i])
159       {
160         // it's different so make the change to the driver and update the cached state
161         mGlStateCache.mVertexAttributeCurrentState[i] = mGlStateCache.mVertexAttributeCachedState[i];
162
163         if(mGlStateCache.mVertexAttributeCurrentState[i])
164         {
165           gl.EnableVertexAttribArray(i);
166         }
167         else
168         {
169           gl.DisableVertexAttribArray(i);
170         }
171       }
172     }
173   }
174
175   /**
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
180    */
181   void SetVertexAttributeLocation(unsigned int location, bool state)
182   {
183     auto& gl = *mController.GetGL();
184
185     if(location >= MAX_ATTRIBUTE_CACHE_SIZE)
186     {
187       // not cached, make the gl call through context
188       if(state)
189       {
190         gl.EnableVertexAttribArray(location);
191       }
192       else
193       {
194         gl.DisableVertexAttribArray(location);
195       }
196     }
197     else
198     {
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;
202     }
203   }
204
205   EglGraphicsController& mController;
206
207   const GLES::PipelineImpl* mCurrentPipeline{nullptr}; ///< Currently bound pipeline
208   const GLES::PipelineImpl* mNewPipeline{nullptr};     ///< New pipeline to be set on flush
209
210   std::vector<Graphics::TextureBinding> mCurrentTextureBindings{};
211   std::vector<Graphics::SamplerBinding> mCurrentSamplerBindings{};
212   GLES::IndexBufferBindingDescriptor    mCurrentIndexBufferBinding{};
213
214   struct VertexBufferBinding
215   {
216     GLES::Buffer* buffer{nullptr};
217     uint32_t      offset{0u};
218   };
219
220   // Currently bound buffers
221   std::vector<VertexBufferBindingDescriptor> mCurrentVertexBufferBindings{};
222
223   // Currently bound UBOs (check if it's needed per program!)
224   std::vector<UniformBufferBindingDescriptor> mCurrentUBOBindings{};
225   UniformBufferBindingDescriptor              mCurrentStandaloneUBOBinding{};
226
227   // Current render pass and render target
228   const GLES::RenderTarget* mCurrentRenderTarget{nullptr};
229   const GLES::RenderPass*   mCurrentRenderPass{nullptr};
230
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
235
236   bool mGlContextCreated{false}; ///< True if the OpenGL context has been created
237
238   EGLContext mNativeDrawContext{0u}; ///< Native rendering EGL context compatible with window context
239
240   EGLSurface mCacheDrawReadSurface{0u};    ///< cached 'read' surface
241   EGLSurface mCacheDrawWriteSurface{0u};   ///< cached 'write' surface
242   EGLContext mCacheEGLGraphicsContext{0u}; ///< cached window context
243 };
244
245 Context::Context(EglGraphicsController& controller)
246 {
247   mImpl = std::make_unique<Impl>(controller);
248 }
249
250 Context::~Context()
251 {
252   // Destroy native rendering context if one exists
253   if(mImpl->mNativeDrawContext)
254   {
255     eglDestroyContext(eglGetCurrentDisplay(), mImpl->mNativeDrawContext);
256     mImpl->mNativeDrawContext = EGL_NO_CONTEXT;
257   }
258 }
259
260 void Context::Flush(bool reset, const GLES::DrawCallDescriptor& drawCall, GLES::TextureDependencyChecker& dependencyChecker)
261 {
262   auto& gl = *mImpl->mController.GetGL();
263
264   static const bool hasGLES3(mImpl->mController.GetGLESVersion() >= GLESVersion::GLES_30);
265
266   // early out if neither current nor new pipelines are set
267   // this behaviour may be valid so no assert
268   if(!mImpl->mCurrentPipeline && !mImpl->mNewPipeline)
269   {
270     return;
271   }
272
273   // Execute states if pipeline is changed
274   const auto currentProgram = mImpl->mCurrentPipeline ? static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program) : nullptr;
275
276   // case when new pipeline has been set
277   const GLES::Program* newProgram = nullptr;
278
279   if(mImpl->mNewPipeline)
280   {
281     newProgram = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
282   }
283
284   if(!currentProgram && !newProgram)
285   {
286     // Early out if we have no program for this pipeline.
287     DALI_LOG_ERROR("No program defined for pipeline\n");
288     return;
289   }
290
291   if(mImpl->mNewPipeline && mImpl->mCurrentPipeline != mImpl->mNewPipeline)
292   {
293     if(!currentProgram || currentProgram->GetImplementation()->GetGlProgram() != newProgram->GetImplementation()->GetGlProgram())
294     {
295       mImpl->mNewPipeline->Bind(newProgram->GetImplementation()->GetGlProgram());
296     }
297
298     // Blend state
299     ResolveBlendState();
300
301     // Resolve rasterization state
302     ResolveRasterizationState();
303   }
304
305   // Resolve uniform buffers
306   ResolveUniformBuffers();
307
308   // Bind textures
309   // Map binding# to sampler location
310   const auto& reflection = !newProgram ? currentProgram->GetReflection() : newProgram->GetReflection();
311   const auto& samplers   = reflection.GetSamplers();
312   for(const auto& binding : mImpl->mCurrentTextureBindings)
313   {
314     auto texture = const_cast<GLES::Texture*>(static_cast<const GLES::Texture*>(binding.texture));
315
316     // Texture may not have been initialized yet...(tbm_surface timing issue?)
317     if(!texture->GetGLTexture())
318     {
319       // Attempt to reinitialize
320       // @todo need to put this somewhere else where it isn't const.
321       // Maybe post it back on end of initialize queue if initialization fails?
322       texture->InitializeResource();
323     }
324
325     // Warning, this may cause glWaitSync to occur on the GPU.
326     dependencyChecker.CheckNeedsSync(this, texture);
327
328     texture->Bind(binding);
329
330     texture->Prepare(); // @todo also non-const.
331
332     if(binding.binding < samplers.size()) // binding maps to texture unit. (texture bindings should also be in binding order)
333     {
334       // Offset is set to the lexical offset within the frag shader, map it to the texture unit
335       // @todo Explicitly set the texture unit through the graphics interface
336       gl.Uniform1i(samplers[binding.binding].location, samplers[binding.binding].offset);
337     }
338   }
339
340   // for each attribute bind vertices
341
342   const auto& pipelineState    = mImpl->mNewPipeline ? mImpl->mNewPipeline->GetCreateInfo() : mImpl->mCurrentPipeline->GetCreateInfo();
343   const auto& vertexInputState = pipelineState.vertexInputState;
344
345   if(hasGLES3)
346   {
347     mImpl->BindProgramVAO(static_cast<const GLES::Program*>(pipelineState.programState->program)->GetImplementation(), *vertexInputState);
348   }
349
350   for(const auto& attr : vertexInputState->attributes)
351   {
352     // Enable location
353     if(!hasGLES3)
354     {
355       mImpl->SetVertexAttributeLocation(attr.location, true);
356     }
357
358     const auto& bufferSlot    = mImpl->mCurrentVertexBufferBindings[attr.binding];
359     const auto& bufferBinding = vertexInputState->bufferBindings[attr.binding];
360
361     auto glesBuffer = bufferSlot.buffer->GetGLBuffer();
362
363     // Bind buffer
364     BindBuffer(GL_ARRAY_BUFFER, glesBuffer);
365
366     gl.VertexAttribPointer(attr.location,
367                            GLVertexFormat(attr.format).size,
368                            GLVertexFormat(attr.format).format,
369                            GL_FALSE,
370                            bufferBinding.stride,
371                            reinterpret_cast<void*>(attr.offset));
372
373     switch(bufferBinding.inputRate)
374     {
375       case Graphics::VertexInputRate::PER_VERTEX:
376       {
377         gl.VertexAttribDivisor(attr.location, 0);
378         break;
379       }
380       case Graphics::VertexInputRate::PER_INSTANCE:
381       {
382         //@todo Get actual instance rate...
383         gl.VertexAttribDivisor(attr.location, 1);
384         break;
385       }
386     }
387   }
388
389   // Resolve topology
390   const auto& ia = pipelineState.inputAssemblyState;
391
392   // Bind uniforms
393
394   // Resolve draw call
395   switch(drawCall.type)
396   {
397     case DrawCallDescriptor::Type::DRAW:
398     {
399       mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
400                                                                 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
401                                                                 mImpl->mGlStateCache.StencilBufferWriteEnabled());
402       // For GLES3+ we use VAO, for GLES2 internal cache
403       if(!hasGLES3)
404       {
405         mImpl->FlushVertexAttributeLocations();
406       }
407
408       if(drawCall.draw.instanceCount == 0)
409       {
410         gl.DrawArrays(GLESTopology(ia->topology),
411                       drawCall.draw.firstVertex,
412                       drawCall.draw.vertexCount);
413       }
414       else
415       {
416         gl.DrawArraysInstanced(GLESTopology(ia->topology),
417                                drawCall.draw.firstVertex,
418                                drawCall.draw.vertexCount,
419                                drawCall.draw.instanceCount);
420       }
421       break;
422     }
423     case DrawCallDescriptor::Type::DRAW_INDEXED:
424     {
425       const auto& binding = mImpl->mCurrentIndexBufferBinding;
426       BindBuffer(GL_ELEMENT_ARRAY_BUFFER, binding.buffer->GetGLBuffer());
427
428       mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
429                                                                 mImpl->mGlStateCache.DepthBufferWriteEnabled(),
430                                                                 mImpl->mGlStateCache.StencilBufferWriteEnabled());
431
432       // For GLES3+ we use VAO, for GLES2 internal cache
433       if(!hasGLES3)
434       {
435         mImpl->FlushVertexAttributeLocations();
436       }
437
438       auto indexBufferFormat = GLIndexFormat(binding.format).format;
439       if(drawCall.drawIndexed.instanceCount == 0)
440       {
441         gl.DrawElements(GLESTopology(ia->topology),
442                         drawCall.drawIndexed.indexCount,
443                         indexBufferFormat,
444                         reinterpret_cast<void*>(binding.offset));
445       }
446       else
447       {
448         gl.DrawElementsInstanced(GLESTopology(ia->topology),
449                                  drawCall.drawIndexed.indexCount,
450                                  indexBufferFormat,
451                                  reinterpret_cast<void*>(binding.offset),
452                                  drawCall.drawIndexed.instanceCount);
453       }
454       break;
455     }
456     case DrawCallDescriptor::Type::DRAW_INDEXED_INDIRECT:
457     {
458       break;
459     }
460   }
461
462   ClearState();
463
464   // Change pipeline
465   if(mImpl->mNewPipeline)
466   {
467     mImpl->mCurrentPipeline = mImpl->mNewPipeline;
468     mImpl->mNewPipeline     = nullptr;
469   }
470 }
471
472 void Context::BindTextures(const Graphics::TextureBinding* bindings, uint32_t count)
473 {
474   // for each texture allocate slot
475   for(auto i = 0u; i < count; ++i)
476   {
477     auto& binding = bindings[i];
478
479     // Resize binding array if needed
480     if(mImpl->mCurrentTextureBindings.size() <= binding.binding)
481     {
482       mImpl->mCurrentTextureBindings.resize(binding.binding + 1);
483     }
484     // Store the binding details
485     mImpl->mCurrentTextureBindings[binding.binding] = binding;
486   }
487 }
488
489 void Context::BindVertexBuffers(const GLES::VertexBufferBindingDescriptor* bindings, uint32_t count)
490 {
491   if(count > mImpl->mCurrentVertexBufferBindings.size())
492   {
493     mImpl->mCurrentVertexBufferBindings.resize(count);
494   }
495   // Copy only set slots
496   std::copy_if(bindings, bindings + count, mImpl->mCurrentVertexBufferBindings.begin(), [](auto& item) {
497     return (nullptr != item.buffer);
498   });
499 }
500
501 void Context::BindIndexBuffer(const IndexBufferBindingDescriptor& indexBufferBinding)
502 {
503   mImpl->mCurrentIndexBufferBinding = indexBufferBinding;
504 }
505
506 void Context::BindPipeline(const GLES::Pipeline* newPipeline)
507 {
508   DALI_ASSERT_ALWAYS(newPipeline && "Invalid pipeline");
509   mImpl->mNewPipeline = &newPipeline->GetPipeline();
510 }
511
512 void Context::BindUniformBuffers(const UniformBufferBindingDescriptor* uboBindings,
513                                  uint32_t                              uboCount,
514                                  const UniformBufferBindingDescriptor& standaloneBindings)
515 {
516   if(standaloneBindings.buffer)
517   {
518     mImpl->mCurrentStandaloneUBOBinding = standaloneBindings;
519   }
520
521   if(uboCount >= mImpl->mCurrentUBOBindings.size())
522   {
523     mImpl->mCurrentUBOBindings.resize(uboCount + 1);
524   }
525
526   auto it = uboBindings;
527   for(auto i = 0u; i < uboCount; ++i)
528   {
529     if(it->buffer)
530     {
531       mImpl->mCurrentUBOBindings[i] = *it;
532     }
533   }
534 }
535
536 void Context::ResolveBlendState()
537 {
538   const auto& currentBlendState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().colorBlendState : nullptr;
539   const auto& newBlendState     = mImpl->mNewPipeline->GetCreateInfo().colorBlendState;
540
541   // TODO: prevent leaking the state
542   if(!newBlendState)
543   {
544     return;
545   }
546
547   auto& gl = *mImpl->mController.GetGL();
548
549   if(!currentBlendState || currentBlendState->blendEnable != newBlendState->blendEnable)
550   {
551     if(newBlendState->blendEnable != mImpl->mGlStateCache.mBlendEnabled)
552     {
553       mImpl->mGlStateCache.mBlendEnabled = newBlendState->blendEnable;
554       newBlendState->blendEnable ? gl.Enable(GL_BLEND) : gl.Disable(GL_BLEND);
555     }
556   }
557
558   if(!newBlendState->blendEnable)
559   {
560     return;
561   }
562
563   BlendFactor newSrcRGB(newBlendState->srcColorBlendFactor);
564   BlendFactor newDstRGB(newBlendState->dstColorBlendFactor);
565   BlendFactor newSrcAlpha(newBlendState->srcAlphaBlendFactor);
566   BlendFactor newDstAlpha(newBlendState->dstAlphaBlendFactor);
567
568   if(!currentBlendState ||
569      currentBlendState->srcColorBlendFactor != newSrcRGB ||
570      currentBlendState->dstColorBlendFactor != newDstRGB ||
571      currentBlendState->srcAlphaBlendFactor != newSrcAlpha ||
572      currentBlendState->dstAlphaBlendFactor != newDstAlpha)
573   {
574     if((mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB != newSrcRGB) ||
575        (mImpl->mGlStateCache.mBlendFuncSeparateDstRGB != newDstRGB) ||
576        (mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha != newSrcAlpha) ||
577        (mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha != newDstAlpha))
578     {
579       mImpl->mGlStateCache.mBlendFuncSeparateSrcRGB   = newSrcRGB;
580       mImpl->mGlStateCache.mBlendFuncSeparateDstRGB   = newDstRGB;
581       mImpl->mGlStateCache.mBlendFuncSeparateSrcAlpha = newSrcAlpha;
582       mImpl->mGlStateCache.mBlendFuncSeparateDstAlpha = newDstAlpha;
583
584       if(newSrcRGB == newSrcAlpha && newDstRGB == newDstAlpha)
585       {
586         gl.BlendFunc(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB));
587       }
588       else
589       {
590         gl.BlendFuncSeparate(GLBlendFunc(newSrcRGB), GLBlendFunc(newDstRGB), GLBlendFunc(newSrcAlpha), GLBlendFunc(newDstAlpha));
591       }
592     }
593   }
594
595   if(!currentBlendState ||
596      currentBlendState->colorBlendOp != newBlendState->colorBlendOp ||
597      currentBlendState->alphaBlendOp != newBlendState->alphaBlendOp)
598   {
599     if(mImpl->mGlStateCache.mBlendEquationSeparateModeRGB != newBlendState->colorBlendOp ||
600        mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha != newBlendState->alphaBlendOp)
601     {
602       mImpl->mGlStateCache.mBlendEquationSeparateModeRGB   = newBlendState->colorBlendOp;
603       mImpl->mGlStateCache.mBlendEquationSeparateModeAlpha = newBlendState->alphaBlendOp;
604
605       if(newBlendState->colorBlendOp == newBlendState->alphaBlendOp)
606       {
607         gl.BlendEquation(GLBlendOp(newBlendState->colorBlendOp));
608         if(newBlendState->colorBlendOp >= Graphics::ADVANCED_BLEND_OPTIONS_START)
609         {
610           gl.BlendBarrier();
611         }
612       }
613       else
614       {
615         gl.BlendEquationSeparate(GLBlendOp(newBlendState->colorBlendOp), GLBlendOp(newBlendState->alphaBlendOp));
616       }
617     }
618   }
619 }
620
621 void Context::ResolveRasterizationState()
622 {
623   const auto& currentRasterizationState = mImpl->mCurrentPipeline ? mImpl->mCurrentPipeline->GetCreateInfo().rasterizationState : nullptr;
624   const auto& newRasterizationState     = mImpl->mNewPipeline->GetCreateInfo().rasterizationState;
625
626   // TODO: prevent leaking the state
627   if(!newRasterizationState)
628   {
629     return;
630   }
631
632   auto& gl = *mImpl->mController.GetGL();
633
634   if(!currentRasterizationState ||
635      currentRasterizationState->cullMode != newRasterizationState->cullMode)
636   {
637     if(mImpl->mGlStateCache.mCullFaceMode != newRasterizationState->cullMode)
638     {
639       mImpl->mGlStateCache.mCullFaceMode = newRasterizationState->cullMode;
640       if(newRasterizationState->cullMode == CullMode::NONE)
641       {
642         gl.Disable(GL_CULL_FACE);
643       }
644       else
645       {
646         gl.Enable(GL_CULL_FACE);
647         gl.CullFace(GLCullMode(newRasterizationState->cullMode));
648       }
649     }
650   }
651   // TODO: implement polygon mode (fill, line, points)
652   //       seems like we don't support it (no glPolygonMode())
653 }
654
655 void Context::ResolveUniformBuffers()
656 {
657   // Resolve standalone uniforms if we have binding
658   if(mImpl->mCurrentStandaloneUBOBinding.buffer)
659   {
660     ResolveStandaloneUniforms();
661   }
662 }
663
664 void Context::ResolveStandaloneUniforms()
665 {
666   // Find reflection for program
667   const GLES::Program* program{nullptr};
668
669   if(mImpl->mNewPipeline)
670   {
671     program = static_cast<const GLES::Program*>(mImpl->mNewPipeline->GetCreateInfo().programState->program);
672   }
673   else if(mImpl->mCurrentPipeline)
674   {
675     program = static_cast<const GLES::Program*>(mImpl->mCurrentPipeline->GetCreateInfo().programState->program);
676   }
677
678   if(program)
679   {
680     const auto ptr = reinterpret_cast<const char*>(mImpl->mCurrentStandaloneUBOBinding.buffer->GetCPUAllocatedAddress()) + mImpl->mCurrentStandaloneUBOBinding.offset;
681     // Update program uniforms
682     program->GetImplementation()->UpdateStandaloneUniformBlock(ptr);
683   }
684 }
685
686 void Context::BeginRenderPass(const BeginRenderPassDescriptor& renderPassBegin)
687 {
688   auto& renderPass   = *renderPassBegin.renderPass;
689   auto& renderTarget = *renderPassBegin.renderTarget;
690
691   const auto& targetInfo = renderTarget.GetCreateInfo();
692
693   auto& gl = *mImpl->mController.GetGL();
694
695   if(targetInfo.surface)
696   {
697     // Bind surface FB
698     BindFrameBuffer(GL_FRAMEBUFFER, 0);
699   }
700   else if(targetInfo.framebuffer)
701   {
702     // bind framebuffer and swap.
703     auto framebuffer = renderTarget.GetFramebuffer();
704     framebuffer->Bind();
705   }
706
707   // clear (ideally cache the setup)
708
709   // In GL we assume that the last attachment is depth/stencil (we may need
710   // to cache extra information inside GLES RenderTarget if we want to be
711   // more specific in case of MRT)
712
713   const auto& attachments = *renderPass.GetCreateInfo().attachments;
714   const auto& color0      = attachments[0];
715   GLuint      mask        = 0;
716
717   if(color0.loadOp == AttachmentLoadOp::CLEAR)
718   {
719     mask |= GL_COLOR_BUFFER_BIT;
720
721     // Set clear color
722     // Something goes wrong here if Alpha mask is GL_TRUE
723     ColorMask(true);
724
725     const auto clearValues = renderPassBegin.clearValues.Ptr();
726
727     if(!Dali::Equals(mImpl->mGlStateCache.mClearColor.r, clearValues[0].color.r) ||
728        !Dali::Equals(mImpl->mGlStateCache.mClearColor.g, clearValues[0].color.g) ||
729        !Dali::Equals(mImpl->mGlStateCache.mClearColor.b, clearValues[0].color.b) ||
730        !Dali::Equals(mImpl->mGlStateCache.mClearColor.a, clearValues[0].color.a) ||
731        !mImpl->mGlStateCache.mClearColorSet)
732     {
733       gl.ClearColor(clearValues[0].color.r,
734                     clearValues[0].color.g,
735                     clearValues[0].color.b,
736                     clearValues[0].color.a);
737
738       mImpl->mGlStateCache.mClearColorSet = true;
739       mImpl->mGlStateCache.mClearColor    = Vector4(clearValues[0].color.r,
740                                                  clearValues[0].color.g,
741                                                  clearValues[0].color.b,
742                                                  clearValues[0].color.a);
743     }
744   }
745
746   // check for depth stencil
747   if(attachments.size() > 1)
748   {
749     const auto& depthStencil = attachments.back();
750     if(depthStencil.loadOp == AttachmentLoadOp::CLEAR)
751     {
752       if(!mImpl->mGlStateCache.mDepthMaskEnabled)
753       {
754         mImpl->mGlStateCache.mDepthMaskEnabled = true;
755         gl.DepthMask(true);
756       }
757       mask |= GL_DEPTH_BUFFER_BIT;
758     }
759     if(depthStencil.stencilLoadOp == AttachmentLoadOp::CLEAR)
760     {
761       if(mImpl->mGlStateCache.mStencilMask != 0xFF)
762       {
763         mImpl->mGlStateCache.mStencilMask = 0xFF;
764         gl.StencilMask(0xFF);
765       }
766       mask |= GL_STENCIL_BUFFER_BIT;
767     }
768   }
769
770   SetScissorTestEnabled(true);
771   gl.Scissor(renderPassBegin.renderArea.x, renderPassBegin.renderArea.y, renderPassBegin.renderArea.width, renderPassBegin.renderArea.height);
772   ClearBuffer(mask, true);
773   SetScissorTestEnabled(false);
774
775   mImpl->mCurrentRenderPass   = &renderPass;
776   mImpl->mCurrentRenderTarget = &renderTarget;
777 }
778
779 void Context::EndRenderPass(GLES::TextureDependencyChecker& dependencyChecker)
780 {
781   if(mImpl->mCurrentRenderTarget)
782   {
783     GLES::Framebuffer* framebuffer = mImpl->mCurrentRenderTarget->GetFramebuffer();
784     if(framebuffer)
785     {
786       auto& gl = *mImpl->mController.GetGL();
787       gl.Flush();
788
789       /* @todo Full dependency checking would need to store textures in Begin, and create
790        * fence objects here; but we're going to draw all fbos on shared context in serial,
791        * so no real need (yet). Might want to consider ensuring order of render passes,
792        * but that needs doing in the controller, and would need doing before ProcessCommandQueues.
793        *
794        * Currently up to the client to create render tasks in the right order.
795        */
796
797       /* Create fence sync objects. Other contexts can then wait on these fences before reading
798        * textures.
799        */
800       dependencyChecker.AddTextures(this, framebuffer);
801     }
802   }
803 }
804
805 void Context::ClearState()
806 {
807   mImpl->mCurrentTextureBindings.clear();
808 }
809
810 void Context::ColorMask(bool enabled)
811 {
812   if(enabled != mImpl->mGlStateCache.mColorMask)
813   {
814     mImpl->mGlStateCache.mColorMask = enabled;
815
816     auto& gl = *mImpl->mController.GetGL();
817     gl.ColorMask(enabled, enabled, enabled, enabled);
818   }
819 }
820
821 void Context::ClearStencilBuffer()
822 {
823   ClearBuffer(GL_STENCIL_BUFFER_BIT, false);
824 }
825
826 void Context::ClearDepthBuffer()
827 {
828   ClearBuffer(GL_DEPTH_BUFFER_BIT, false);
829 }
830
831 void Context::ClearBuffer(uint32_t mask, bool forceClear)
832 {
833   mask = mImpl->mGlStateCache.mFrameBufferStateCache.GetClearMask(mask, forceClear, mImpl->mGlStateCache.mScissorTestEnabled);
834   if(mask > 0)
835   {
836     auto& gl = *mImpl->mController.GetGL();
837     gl.Clear(mask);
838   }
839 }
840
841 void Context::InvalidateDepthStencilBuffers()
842 {
843   auto& gl = *mImpl->mController.GetGL();
844
845   GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
846   gl.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
847 }
848
849 void Context::SetScissorTestEnabled(bool scissorEnabled)
850 {
851   if(mImpl->mGlStateCache.mScissorTestEnabled != scissorEnabled)
852   {
853     mImpl->mGlStateCache.mScissorTestEnabled = scissorEnabled;
854
855     auto& gl = *mImpl->mController.GetGL();
856     if(scissorEnabled)
857     {
858       gl.Enable(GL_SCISSOR_TEST);
859     }
860     else
861     {
862       gl.Disable(GL_SCISSOR_TEST);
863     }
864   }
865 }
866
867 void Context::SetStencilTestEnable(bool stencilEnable)
868 {
869   if(stencilEnable != mImpl->mGlStateCache.mStencilBufferEnabled)
870   {
871     mImpl->mGlStateCache.mStencilBufferEnabled = stencilEnable;
872
873     auto& gl = *mImpl->mController.GetGL();
874     if(stencilEnable)
875     {
876       gl.Enable(GL_STENCIL_TEST);
877     }
878     else
879     {
880       gl.Disable(GL_STENCIL_TEST);
881     }
882   }
883 }
884
885 void Context::StencilMask(uint32_t writeMask)
886 {
887   if(writeMask != mImpl->mGlStateCache.mStencilMask)
888   {
889     mImpl->mGlStateCache.mStencilMask = writeMask;
890
891     auto& gl = *mImpl->mController.GetGL();
892     gl.StencilMask(writeMask);
893   }
894 }
895
896 void Context::StencilFunc(Graphics::CompareOp compareOp,
897                           uint32_t            reference,
898                           uint32_t            compareMask)
899 {
900   if(compareOp != mImpl->mGlStateCache.mStencilFunc ||
901      reference != mImpl->mGlStateCache.mStencilFuncRef ||
902      compareMask != mImpl->mGlStateCache.mStencilFuncMask)
903   {
904     mImpl->mGlStateCache.mStencilFunc     = compareOp;
905     mImpl->mGlStateCache.mStencilFuncRef  = reference;
906     mImpl->mGlStateCache.mStencilFuncMask = compareMask;
907
908     auto& gl = *mImpl->mController.GetGL();
909     gl.StencilFunc(GLCompareOp(compareOp).op, reference, compareMask);
910   }
911 }
912
913 void Context::StencilOp(Graphics::StencilOp failOp,
914                         Graphics::StencilOp depthFailOp,
915                         Graphics::StencilOp passOp)
916 {
917   if(failOp != mImpl->mGlStateCache.mStencilOpFail ||
918      depthFailOp != mImpl->mGlStateCache.mStencilOpDepthFail ||
919      passOp != mImpl->mGlStateCache.mStencilOpDepthPass)
920   {
921     mImpl->mGlStateCache.mStencilOpFail      = failOp;
922     mImpl->mGlStateCache.mStencilOpDepthFail = depthFailOp;
923     mImpl->mGlStateCache.mStencilOpDepthPass = passOp;
924
925     auto& gl = *mImpl->mController.GetGL();
926     gl.StencilOp(GLStencilOp(failOp).op, GLStencilOp(depthFailOp).op, GLStencilOp(passOp).op);
927   }
928 }
929
930 void Context::SetDepthCompareOp(Graphics::CompareOp compareOp)
931 {
932   if(compareOp != mImpl->mGlStateCache.mDepthFunction)
933   {
934     mImpl->mGlStateCache.mDepthFunction = compareOp;
935     auto& gl                            = *mImpl->mController.GetGL();
936     gl.DepthFunc(GLCompareOp(compareOp).op);
937   }
938 }
939
940 void Context::SetDepthTestEnable(bool depthTestEnable)
941 {
942   if(depthTestEnable != mImpl->mGlStateCache.mDepthBufferEnabled)
943   {
944     mImpl->mGlStateCache.mDepthBufferEnabled = depthTestEnable;
945
946     auto& gl = *mImpl->mController.GetGL();
947     if(depthTestEnable)
948     {
949       gl.Enable(GL_DEPTH_TEST);
950     }
951     else
952     {
953       gl.Disable(GL_DEPTH_TEST);
954     }
955   }
956 }
957
958 void Context::SetDepthWriteEnable(bool depthWriteEnable)
959 {
960   if(depthWriteEnable != mImpl->mGlStateCache.mDepthMaskEnabled)
961   {
962     mImpl->mGlStateCache.mDepthMaskEnabled = depthWriteEnable;
963
964     auto& gl = *mImpl->mController.GetGL();
965     gl.DepthMask(depthWriteEnable);
966   }
967 }
968
969 void Context::ActiveTexture(uint32_t textureBindingIndex)
970 {
971   if(mImpl->mGlStateCache.mActiveTextureUnit != textureBindingIndex)
972   {
973     mImpl->mGlStateCache.mActiveTextureUnit = textureBindingIndex;
974
975     auto& gl = *mImpl->mController.GetGL();
976     gl.ActiveTexture(GL_TEXTURE0 + textureBindingIndex);
977   }
978 }
979
980 void Context::BindTexture(GLenum target, BoundTextureType textureTypeId, uint32_t textureId)
981 {
982   uint32_t typeId = static_cast<uint32_t>(textureTypeId);
983   if(mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] != textureId)
984   {
985     mImpl->mGlStateCache.mBoundTextureId[mImpl->mGlStateCache.mActiveTextureUnit][typeId] = textureId;
986
987     auto& gl = *mImpl->mController.GetGL();
988     gl.BindTexture(target, textureId);
989   }
990 }
991
992 void Context::GenerateMipmap(GLenum target)
993 {
994   auto& gl = *mImpl->mController.GetGL();
995   gl.GenerateMipmap(target);
996 }
997
998 void Context::BindBuffer(GLenum target, uint32_t bufferId)
999 {
1000   switch(target)
1001   {
1002     case GL_ARRAY_BUFFER:
1003     {
1004       if(mImpl->mGlStateCache.mBoundArrayBufferId == bufferId)
1005       {
1006         return;
1007       }
1008       mImpl->mGlStateCache.mBoundArrayBufferId = bufferId;
1009       break;
1010     }
1011     case GL_ELEMENT_ARRAY_BUFFER:
1012     {
1013       if(mImpl->mGlStateCache.mBoundElementArrayBufferId == bufferId)
1014       {
1015         return;
1016       }
1017       mImpl->mGlStateCache.mBoundElementArrayBufferId = bufferId;
1018       break;
1019     }
1020   }
1021
1022   // Cache miss. Bind buffer.
1023   auto& gl = *mImpl->mController.GetGL();
1024   gl.BindBuffer(target, bufferId);
1025 }
1026
1027 void Context::DrawBuffers(uint32_t count, const GLenum* buffers)
1028 {
1029   mImpl->mGlStateCache.mFrameBufferStateCache.DrawOperation(mImpl->mGlStateCache.mColorMask,
1030                                                             mImpl->mGlStateCache.DepthBufferWriteEnabled(),
1031                                                             mImpl->mGlStateCache.StencilBufferWriteEnabled());
1032
1033   auto& gl = *mImpl->mController.GetGL();
1034   gl.DrawBuffers(count, buffers);
1035 }
1036
1037 void Context::BindFrameBuffer(GLenum target, uint32_t bufferId)
1038 {
1039   mImpl->mGlStateCache.mFrameBufferStateCache.SetCurrentFrameBuffer(bufferId);
1040
1041   auto& gl = *mImpl->mController.GetGL();
1042   gl.BindFramebuffer(target, bufferId);
1043 }
1044
1045 void Context::GenFramebuffers(uint32_t count, uint32_t* framebuffers)
1046 {
1047   auto& gl = *mImpl->mController.GetGL();
1048   gl.GenFramebuffers(count, framebuffers);
1049
1050   mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersCreated(count, framebuffers);
1051 }
1052
1053 void Context::DeleteFramebuffers(uint32_t count, uint32_t* framebuffers)
1054 {
1055   mImpl->mGlStateCache.mFrameBufferStateCache.FrameBuffersDeleted(count, framebuffers);
1056
1057   auto& gl = *mImpl->mController.GetGL();
1058   gl.DeleteFramebuffers(count, framebuffers);
1059 }
1060
1061 GLStateCache& Context::GetGLStateCache()
1062 {
1063   return mImpl->mGlStateCache;
1064 }
1065
1066 void Context::GlContextCreated()
1067 {
1068   if(!mImpl->mGlContextCreated)
1069   {
1070     mImpl->mGlContextCreated = true;
1071
1072     // Set the initial GL state
1073     mImpl->InitializeGlState();
1074   }
1075 }
1076
1077 void Context::GlContextDestroyed()
1078 {
1079   mImpl->mGlContextCreated = false;
1080 }
1081
1082 void Context::InvalidateCachedPipeline(GLES::Pipeline* pipeline)
1083 {
1084   // Since the pipeline is deleted, invalidate the cached pipeline.
1085   if(mImpl->mCurrentPipeline == &pipeline->GetPipeline())
1086   {
1087     mImpl->mCurrentPipeline = nullptr;
1088   }
1089
1090   // Remove cached VAO map
1091   auto* gl = mImpl->mController.GetGL();
1092   if(gl)
1093   {
1094     const auto* program = pipeline->GetCreateInfo().programState->program;
1095     if(program)
1096     {
1097       const auto* programImpl = static_cast<const GLES::Program*>(program)->GetImplementation();
1098       if(programImpl)
1099       {
1100         auto iter = mImpl->mProgramVAOMap.find(programImpl);
1101         if(iter != mImpl->mProgramVAOMap.end())
1102         {
1103           for(auto& attributeHashPair : iter->second)
1104           {
1105             auto vao = attributeHashPair.second;
1106             gl->DeleteVertexArrays(1, &vao);
1107             if(mImpl->mProgramVAOCurrentState == vao)
1108             {
1109               mImpl->mProgramVAOCurrentState = 0u;
1110             }
1111           }
1112           mImpl->mProgramVAOMap.erase(iter);
1113         }
1114       }
1115     }
1116   }
1117 }
1118
1119 void Context::PrepareForNativeRendering()
1120 {
1121   // this should be pretty much constant
1122   auto display     = eglGetCurrentDisplay();
1123   auto drawSurface = eglGetCurrentSurface(EGL_DRAW);
1124   auto readSurface = eglGetCurrentSurface(EGL_READ);
1125   auto context     = eglGetCurrentContext();
1126
1127   // push the surface and context data to the impl
1128   // It's needed to restore context
1129   if(!mImpl->mCacheEGLGraphicsContext)
1130   {
1131     mImpl->mCacheDrawWriteSurface   = drawSurface;
1132     mImpl->mCacheDrawReadSurface    = readSurface;
1133     mImpl->mCacheEGLGraphicsContext = context;
1134   }
1135
1136   if(!mImpl->mNativeDrawContext)
1137   {
1138     EGLint configId{0u};
1139     eglQueryContext(display, mImpl->mController.GetSharedContext(), EGL_CONFIG_ID, &configId);
1140
1141     EGLint configAttribs[3];
1142     configAttribs[0] = EGL_CONFIG_ID;
1143     configAttribs[1] = configId;
1144     configAttribs[2] = EGL_NONE;
1145
1146     EGLConfig config;
1147     EGLint    numConfigs;
1148     if(eglChooseConfig(display, configAttribs, &config, 1, &numConfigs) != EGL_TRUE)
1149     {
1150       DALI_LOG_ERROR("eglChooseConfig failed!\n");
1151       return;
1152     }
1153
1154     auto version = int(mImpl->mController.GetGLESVersion());
1155
1156     std::vector<EGLint> attribs;
1157     attribs.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
1158     attribs.push_back(version / 10);
1159     attribs.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
1160     attribs.push_back(version % 10);
1161     attribs.push_back(EGL_NONE);
1162
1163     mImpl->mNativeDrawContext = eglCreateContext(display, config, mImpl->mController.GetSharedContext(), attribs.data());
1164     if(mImpl->mNativeDrawContext == EGL_NO_CONTEXT)
1165     {
1166       DALI_LOG_ERROR("eglCreateContext failed!\n");
1167       return;
1168     }
1169   }
1170
1171   eglMakeCurrent(display, drawSurface, readSurface, mImpl->mNativeDrawContext);
1172 }
1173
1174 void Context::RestoreFromNativeRendering()
1175 {
1176   auto display = eglGetCurrentDisplay();
1177
1178   // bring back original context
1179   eglMakeCurrent(display, mImpl->mCacheDrawWriteSurface, mImpl->mCacheDrawReadSurface, mImpl->mCacheEGLGraphicsContext);
1180 }
1181
1182 } // namespace Dali::Graphics::GLES