8fe7b7317b0b588d6a26af6bccb1de1b0816fa7e
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles-impl / egl-graphics-controller.cpp
1 /*
2  * Copyright (c) 2021 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 // CLASS HEADER
18 #include <dali/internal/graphics/gles-impl/egl-graphics-controller.h>
19
20 // INTERNAL INCLUDES
21 #include <dali/integration-api/debug.h>
22 #include <dali/integration-api/gl-abstraction.h>
23 #include <dali/integration-api/gl-defines.h>
24 #include <dali/internal/graphics/gles-impl/gles-graphics-command-buffer.h>
25 #include <dali/internal/graphics/gles-impl/gles-graphics-pipeline.h>
26 #include <dali/internal/graphics/gles-impl/gles-graphics-shader.h>
27 #include <dali/internal/graphics/gles-impl/gles-graphics-texture.h>
28 #include <dali/internal/graphics/gles-impl/gles-graphics-types.h>
29 #include <dali/internal/graphics/gles-impl/gles3-graphics-memory.h>
30 #include <dali/public-api/common/dali-common.h>
31 #include "gles-graphics-program.h"
32
33 namespace Dali::Graphics
34 {
35 namespace
36 {
37 /**
38  * @brief Custom deleter for all Graphics objects created
39  * with use of the Controller.
40  *
41  * When Graphics object dies the unique pointer (Graphics::UniquePtr)
42  * doesn't destroy it directly but passes the ownership back
43  * to the Controller. The GLESDeleter is responsible for passing
44  * the object to the discard queue (by calling Resource::DiscardResource()).
45  */
46 template<typename T>
47 struct GLESDeleter
48 {
49   GLESDeleter() = default;
50
51   void operator()(T* object)
52   {
53     // Discard resource (add it to discard queue)
54     object->DiscardResource();
55   }
56 };
57
58 /**
59  * @brief Helper function allocating graphics object
60  *
61  * @param[in] info Create info structure
62  * @param[in] controller Controller object
63  * @param[out] out Unique pointer to the return object
64  */
65 template<class GLESType, class GfxCreateInfo, class T>
66 auto NewObject(const GfxCreateInfo& info, EglGraphicsController& controller, T&& oldObject)
67 {
68   // Use allocator
69   using Type = typename T::element_type;
70   using UPtr = Graphics::UniquePtr<Type>;
71   if(info.allocationCallbacks)
72   {
73     auto* memory = info.allocationCallbacks->allocCallback(
74       sizeof(GLESType),
75       0,
76       info.allocationCallbacks->userData);
77     return UPtr(new(memory) GLESType(info, controller), GLESDeleter<GLESType>());
78   }
79   else // Use standard allocator
80   {
81     return UPtr(new GLESType(info, controller), GLESDeleter<GLESType>());
82   }
83 }
84
85 template<class T0, class T1>
86 T0* CastObject(T1* apiObject)
87 {
88   return static_cast<T0*>(apiObject);
89 }
90
91 } // namespace
92
93 EglGraphicsController::~EglGraphicsController() = default;
94
95 void EglGraphicsController::InitializeGLES(Integration::GlAbstraction& glAbstraction)
96 {
97   DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #1\n");
98   mGlAbstraction = &glAbstraction;
99   mContext       = std::make_unique<GLES::Context>(*this);
100 }
101
102 void EglGraphicsController::Initialize(Integration::GlSyncAbstraction&          glSyncAbstraction,
103                                        Integration::GlContextHelperAbstraction& glContextHelperAbstraction)
104 {
105   DALI_LOG_RELEASE_INFO("Initializing New Graphics Controller #2\n");
106   mGlSyncAbstraction          = &glSyncAbstraction;
107   mGlContextHelperAbstraction = &glContextHelperAbstraction;
108 }
109
110 void EglGraphicsController::SubmitCommandBuffers(const SubmitInfo& submitInfo)
111 {
112   for(auto& cmdbuf : submitInfo.cmdBuffer)
113   {
114     // Push command buffers
115     mCommandQueue.push(static_cast<GLES::CommandBuffer*>(cmdbuf));
116   }
117
118   // If flush bit set, flush all pending tasks
119   if(submitInfo.flags & (0 | SubmitFlagBits::FLUSH))
120   {
121     Flush();
122   }
123 }
124
125 Integration::GlAbstraction& EglGraphicsController::GetGlAbstraction()
126 {
127   DALI_ASSERT_DEBUG(mGlAbstraction && "Graphics controller not initialized");
128   return *mGlAbstraction;
129 }
130
131 Integration::GlSyncAbstraction& EglGraphicsController::GetGlSyncAbstraction()
132 {
133   DALI_ASSERT_DEBUG(mGlSyncAbstraction && "Graphics controller not initialized");
134   return *mGlSyncAbstraction;
135 }
136
137 Integration::GlContextHelperAbstraction& EglGraphicsController::GetGlContextHelperAbstraction()
138 {
139   DALI_ASSERT_DEBUG(mGlContextHelperAbstraction && "Graphics controller not initialized");
140   return *mGlContextHelperAbstraction;
141 }
142
143 Graphics::UniquePtr<CommandBuffer>
144 EglGraphicsController::CreateCommandBuffer(const CommandBufferCreateInfo&       commandBufferCreateInfo,
145                                            Graphics::UniquePtr<CommandBuffer>&& oldCommandBuffer)
146 {
147   return NewObject<GLES::CommandBuffer>(commandBufferCreateInfo, *this, std::move(oldCommandBuffer));
148 }
149
150 Graphics::UniquePtr<Texture>
151 EglGraphicsController::CreateTexture(const TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Texture>&& oldTexture)
152 {
153   return NewObject<GLES::Texture>(textureCreateInfo, *this, std::move(oldTexture));
154 }
155
156 Graphics::UniquePtr<Buffer>
157 EglGraphicsController::CreateBuffer(const BufferCreateInfo& bufferCreateInfo, Graphics::UniquePtr<Buffer>&& oldBuffer)
158 {
159   return NewObject<GLES::Buffer>(bufferCreateInfo, *this, std::move(oldBuffer));
160 }
161
162 Graphics::UniquePtr<Pipeline> EglGraphicsController::CreatePipeline(const PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
163 {
164   // Create pipeline cache if needed
165   if(!mPipelineCache)
166   {
167     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
168   }
169
170   return mPipelineCache->GetPipeline(pipelineCreateInfo, std::move(oldPipeline));
171 }
172
173 Graphics::UniquePtr<Program> EglGraphicsController::CreateProgram(const ProgramCreateInfo& programCreateInfo, UniquePtr<Program>&& oldProgram)
174 {
175   // Create program cache if needed
176   if(!mPipelineCache)
177   {
178     mPipelineCache = std::make_unique<GLES::PipelineCache>(*this);
179   }
180
181   return mPipelineCache->GetProgram(programCreateInfo, std::move(oldProgram));
182 }
183
184 Graphics::UniquePtr<Shader> EglGraphicsController::CreateShader(const ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Shader>&& oldShader)
185 {
186   return NewObject<GLES::Shader>(shaderCreateInfo, *this, std::move(oldShader));
187 }
188
189 Graphics::UniquePtr<Sampler> EglGraphicsController::CreateSampler(const SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Sampler>&& oldSampler)
190 {
191   return NewObject<GLES::Sampler>(samplerCreateInfo, *this, std::move(oldSampler));
192 }
193
194 const Graphics::Reflection& EglGraphicsController::GetProgramReflection(const Graphics::Program& program)
195 {
196   return static_cast<const Graphics::GLES::Program*>(&program)->GetReflection();
197 }
198
199 void EglGraphicsController::AddTexture(GLES::Texture& texture)
200 {
201   // Assuming we are on the correct context
202   mCreateTextureQueue.push(&texture);
203 }
204
205 void EglGraphicsController::AddBuffer(GLES::Buffer& buffer)
206 {
207   // Assuming we are on the correct context
208   mCreateBufferQueue.push(&buffer);
209 }
210
211 void EglGraphicsController::ProcessDiscardQueues()
212 {
213   // Process textures
214   ProcessDiscardQueue<GLES::Texture>(mDiscardTextureQueue);
215
216   // Process buffers
217   ProcessDiscardQueue<GLES::Buffer>(mDiscardBufferQueue);
218
219   // Process pipelines
220   ProcessDiscardQueue<GLES::Pipeline>(mDiscardPipelineQueue);
221
222   // Process programs
223   ProcessDiscardQueue<GLES::Program>(mDiscardProgramQueue);
224
225   // Process shaders
226   ProcessDiscardQueue<GLES::Shader>(mDiscardShaderQueue);
227
228   // Process samplers
229   ProcessDiscardQueue<GLES::Sampler>(mDiscardSamplerQueue);
230
231   // Process command buffers
232   ProcessDiscardQueue<GLES::CommandBuffer>(mDiscardCommandBufferQueue);
233 }
234
235 void EglGraphicsController::ProcessCreateQueues()
236 {
237   // Process textures
238   ProcessCreateQueue(mCreateTextureQueue);
239
240   // Process buffers
241   ProcessCreateQueue(mCreateBufferQueue);
242 }
243
244 void EglGraphicsController::ProcessCommandQueues()
245 {
246   // TODO: command queue per context, sync between queues should be
247   // done externally
248
249   while(!mCommandQueue.empty())
250   {
251     auto cmdBuf = mCommandQueue.front();
252     mCommandQueue.pop();
253
254     for(auto& cmd : cmdBuf->GetCommands())
255     {
256       // process command
257       switch(cmd.type)
258       {
259         case GLES::CommandType::FLUSH:
260         {
261           // Nothing to do here
262           break;
263         }
264         case GLES::CommandType::BIND_TEXTURES:
265         {
266           mContext->BindTextures(cmd.bindTextures.textureBindings);
267           break;
268         }
269         case GLES::CommandType::BIND_VERTEX_BUFFERS:
270         {
271           auto& bindings = cmd.bindVertexBuffers.vertexBufferBindings;
272           mContext->BindVertexBuffers(bindings);
273           break;
274         }
275         case GLES::CommandType::BIND_UNIFORM_BUFFER:
276         {
277           auto& bindings = cmd.bindUniformBuffers;
278           mContext->BindUniformBuffers(bindings.uniformBufferBindings, bindings.standaloneUniformsBufferBinding);
279           break;
280         }
281         case GLES::CommandType::BIND_INDEX_BUFFER:
282         {
283           mContext->BindIndexBuffer(cmd.bindIndexBuffer);
284           break;
285         }
286         case GLES::CommandType::BIND_SAMPLERS:
287         {
288           break;
289         }
290         case GLES::CommandType::BIND_PIPELINE:
291         {
292           mContext->BindPipeline(cmd.bindPipeline.pipeline);
293           break;
294         }
295         case GLES::CommandType::DRAW:
296         {
297           mContext->Flush(false, cmd.draw);
298           break;
299         }
300         case GLES::CommandType::DRAW_INDEXED:
301         {
302           mContext->Flush(false, cmd.draw);
303           break;
304         }
305         case GLES::CommandType::DRAW_INDEXED_INDIRECT:
306         {
307           mContext->Flush(false, cmd.draw);
308           break;
309         }
310         case GLES::CommandType::SET_SCISSOR: // @todo Consider correcting for orientation here?
311         {
312           mGlAbstraction->Scissor(cmd.scissor.region.x, cmd.scissor.region.y, cmd.scissor.region.width, cmd.scissor.region.height);
313           break;
314         }
315         case GLES::CommandType::SET_SCISSOR_TEST:
316         {
317           if(cmd.scissorTest.enable)
318           {
319             mGlAbstraction->Enable(GL_SCISSOR_TEST);
320           }
321           else
322           {
323             mGlAbstraction->Disable(GL_SCISSOR_TEST);
324           }
325           break;
326         }
327         case GLES::CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
328         {
329           mGlAbstraction->Viewport(cmd.viewport.region.x, cmd.viewport.region.y, cmd.viewport.region.width, cmd.viewport.region.height);
330           break;
331         }
332       }
333     }
334   }
335 }
336
337 void EglGraphicsController::ProcessTextureUpdateQueue()
338 {
339   while(!mTextureUpdateRequests.empty())
340   {
341     TextureUpdateRequest& request = mTextureUpdateRequests.front();
342
343     auto& info   = request.first;
344     auto& source = request.second;
345
346     if(source.sourceType == Graphics::TextureUpdateSourceInfo::Type::MEMORY)
347     {
348       // GPU memory must be already allocated (glTexImage2D())
349       auto*       texture    = static_cast<GLES::Texture*>(info.dstTexture);
350       const auto& createInfo = texture->GetCreateInfo();
351
352       mGlAbstraction->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
353
354       mGlAbstraction->BindTexture(GL_TEXTURE_2D, texture->GetGLTexture());
355       mGlAbstraction->TexSubImage2D(GL_TEXTURE_2D,
356                                     info.level,
357                                     info.dstOffset2D.x,
358                                     info.dstOffset2D.y,
359                                     info.srcExtent2D.width,
360                                     info.srcExtent2D.height,
361                                     GLES::GLTextureFormatType(createInfo.format).format,
362                                     GLES::GLTextureFormatType(createInfo.format).type,
363                                     source.memorySource.memory);
364
365       // free staging memory
366       free(source.memorySource.memory);
367     }
368     else
369     {
370       // TODO: other sources
371     }
372
373     mTextureUpdateRequests.pop();
374   }
375 }
376
377 void EglGraphicsController::UpdateTextures(const std::vector<TextureUpdateInfo>&       updateInfoList,
378                                            const std::vector<TextureUpdateSourceInfo>& sourceList)
379 {
380   // Store updates
381   for(auto& info : updateInfoList)
382   {
383     mTextureUpdateRequests.push(std::make_pair(info, sourceList[info.srcReference]));
384     auto& pair = mTextureUpdateRequests.back();
385     switch(pair.second.sourceType)
386     {
387       case Graphics::TextureUpdateSourceInfo::Type::MEMORY:
388       {
389         auto& info   = pair.first;
390         auto& source = pair.second;
391
392         // allocate staging memory and copy the data
393         // TODO: using PBO with GLES3, this is just naive
394         // oldschool way
395
396         char* stagingBuffer = reinterpret_cast<char*>(malloc(info.srcSize));
397         std::copy(&reinterpret_cast<char*>(source.memorySource.memory)[info.srcOffset],
398                   reinterpret_cast<char*>(source.memorySource.memory) + info.srcSize,
399                   stagingBuffer);
400
401         // store staging buffer
402         source.memorySource.memory = stagingBuffer;
403         break;
404       }
405       case Graphics::TextureUpdateSourceInfo::Type::BUFFER:
406       {
407         // TODO, with PBO support
408         break;
409       }
410       case Graphics::TextureUpdateSourceInfo::Type::TEXTURE:
411       {
412         // TODO texture 2 texture in-GPU copy
413         break;
414       }
415     }
416   }
417 }
418
419 Graphics::UniquePtr<Memory> EglGraphicsController::MapBufferRange(const MapBufferInfo& mapInfo)
420 {
421   // Mapping buffer requires the object to be created NOW
422   // Workaround - flush now, otherwise there will be given a staging buffer
423   // in case when the buffer is not there yet
424   ProcessCreateQueues();
425
426   if(GetGLESVersion() < GLES::GLESVersion::GLES_30)
427   {
428     return Graphics::UniquePtr<Memory>(new GLES::Memory2(mapInfo, *this));
429   }
430   else
431   {
432     return Graphics::UniquePtr<Memory>(new GLES::Memory3(mapInfo, *this));
433   }
434 }
435
436 bool EglGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
437 {
438   return static_cast<GLES::Program*>(&program)->GetImplementation()->GetParameter(parameterId, outData);
439 }
440
441 GLES::PipelineCache& EglGraphicsController::GetPipelineCache() const
442 {
443   return *mPipelineCache;
444 }
445
446 } // namespace Dali::Graphics