[dali_2.3.25] Merge branch 'devel/master'
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-texture.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 // CLASS HEADER
18 #include <dali/internal/render/renderers/render-texture.h>
19
20 // EXTERNAL INCLUDES
21 #include <math.h> //floor, log2
22
23 // INTERNAL INCLUDES
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/common/memory-pool-object-allocator.h>
26 #include <dali/internal/render/common/render-manager.h>
27
28 namespace Dali
29 {
30 namespace Internal
31 {
32 namespace Render
33 {
34 namespace
35 {
36 #if defined(DEBUG_ENABLED)
37 Debug::Filter* gTextureFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TEXTURE");
38 #endif
39
40 // Memory pool used to allocate new textures. Memory used by this pool will be released when shutting down DALi
41 MemoryPoolObjectAllocator<Texture>& GetTextureMemoryPool()
42 {
43   static MemoryPoolObjectAllocator<Texture> gTextureMemoryPool;
44   return gTextureMemoryPool;
45 }
46
47 } //Unnamed namespace
48
49 TextureKey Texture::NewKey(Type type, Pixel::Format format, ImageDimensions size)
50 {
51   void* ptr = GetTextureMemoryPool().AllocateRawThreadSafe();
52   auto  key = GetTextureMemoryPool().GetKeyFromPtr(static_cast<Texture*>(ptr));
53   new(ptr) Texture(type, format, size);
54
55   return TextureKey(key);
56 }
57
58 TextureKey Texture::NewKey(NativeImageInterfacePtr nativeImageInterface)
59 {
60   void* ptr = GetTextureMemoryPool().AllocateRawThreadSafe();
61   auto  key = GetTextureMemoryPool().GetKeyFromPtr(static_cast<Texture*>(ptr));
62   new(ptr) Texture(nativeImageInterface);
63
64   return TextureKey(key);
65 }
66
67 TextureKey Texture::NewKey(Type type, uint32_t resourceId)
68 {
69   void* ptr = GetTextureMemoryPool().AllocateRawThreadSafe();
70   auto  key = GetTextureMemoryPool().GetKeyFromPtr(static_cast<Texture*>(ptr));
71   new(ptr) Texture(type, resourceId);
72
73   return TextureKey(key);
74 }
75
76 Texture::Texture(Type type, Pixel::Format format, ImageDimensions size)
77 : mGraphicsController(nullptr),
78   mRenderManager(nullptr),
79   mGraphicsTexture(nullptr),
80   mNativeImage(),
81   mSampler(),
82   mPixelFormat(format),
83   mWidth(size.GetWidth()),
84   mHeight(size.GetHeight()),
85   mResourceId(0u),
86   mType(type),
87   mHasAlpha(HasAlpha(format)),
88   mUpdated(true),
89   mUseUploadedParameter(mWidth == 0u && mHeight == 0u && mPixelFormat == Pixel::INVALID)
90 {
91 }
92
93 Texture::Texture(NativeImageInterfacePtr nativeImageInterface)
94 : mGraphicsController(nullptr),
95   mRenderManager(nullptr),
96   mGraphicsTexture(nullptr),
97   mNativeImage(nativeImageInterface),
98   mSampler(),
99   mPixelFormat(Pixel::RGBA8888),
100   mWidth(static_cast<uint16_t>(nativeImageInterface->GetWidth())),   // ignoring overflow, not happening in practice
101   mHeight(static_cast<uint16_t>(nativeImageInterface->GetHeight())), // ignoring overflow, not happening in practice
102   mResourceId(0u),
103   mType(TextureType::TEXTURE_2D),
104   mHasAlpha(nativeImageInterface->RequiresBlending()),
105   mUpdated(true),
106   mUseUploadedParameter(false)
107 {
108 }
109
110 Texture::Texture(Type type, uint32_t resourceId)
111 : mGraphicsController(nullptr),
112   mRenderManager(nullptr),
113   mGraphicsTexture(nullptr),
114   mNativeImage(),
115   mSampler(),
116   mPixelFormat(Pixel::INVALID),
117   mWidth(0u),
118   mHeight(0u),
119   mResourceId(resourceId),
120   mType(type),
121   mHasAlpha(true), ///< Since we don't assume what kind of texture will be uploaded in this case.
122   mUpdated(true),
123   mUseUploadedParameter(true)
124 {
125 }
126
127 Texture::~Texture() = default;
128
129 void Texture::operator delete(void* ptr)
130 {
131   GetTextureMemoryPool().FreeThreadSafe(static_cast<Texture*>(ptr));
132 }
133
134 Render::Texture* Texture::Get(TextureKey::KeyType key)
135 {
136   return GetTextureMemoryPool().GetPtrFromKey(key);
137 }
138
139 void Texture::Initialize(Graphics::Controller& graphicsController, SceneGraph::RenderManager& renderManager)
140 {
141   mGraphicsController = &graphicsController;
142   mRenderManager      = &renderManager;
143   if(mNativeImage)
144   {
145     Create(static_cast<uint32_t>(Graphics::TextureUsageFlagBits::SAMPLE));
146   }
147
148   if(mResourceId != 0u && mGraphicsController->GetTextureFromResourceId(mResourceId))
149   {
150     // Take ownership from graphics controller
151     mGraphicsTexture = std::move(mGraphicsController->ReleaseTextureFromResourceId(mResourceId));
152     // Now we take on the Graphics::Texture ownership. We don't need to keep mResourceId anymore.
153     mResourceId = 0u;
154   }
155 }
156
157 void Texture::Destroy()
158 {
159   if(mResourceId != 0u && mGraphicsTexture.get() == nullptr)
160   {
161     // We still don't take texture ownership from controller before.
162     // Discard graphics object now.
163     mGraphicsController->DiscardTextureFromResourceId(mResourceId);
164     mResourceId = 0u;
165   }
166
167   mGraphicsTexture.reset();
168 }
169
170 Graphics::Texture* Texture::GetGraphicsObject()
171 {
172   if(mResourceId != 0u && mGraphicsTexture.get() == nullptr)
173   {
174     // The ownership of Graphics::Texture is on Graphics::Controller. Ask to controller.
175     Graphics::Texture* graphicsTexturePtr = nullptr;
176     if(mGraphicsController)
177     {
178       graphicsTexturePtr = mGraphicsController->GetTextureFromResourceId(mResourceId);
179
180       if(graphicsTexturePtr)
181       {
182         // Take ownership from graphics controller
183         mGraphicsTexture = std::move(mGraphicsController->ReleaseTextureFromResourceId(mResourceId));
184         // (Partial update) Do not make mResourceId as 0 until we update mLatestUsedGraphicsTexture.
185         NotifyTextureUpdated();
186       }
187     }
188     DALI_LOG_INFO(gTextureFilter, Debug::General, "Render::Texture(%p)::GetGraphicsObject() = %p [with resource id : %u]\n", this, graphicsTexturePtr, mResourceId);
189
190     return graphicsTexturePtr;
191   }
192   else
193   {
194     DALI_LOG_INFO(gTextureFilter, Debug::General, "Render::Texture(%p)::GetGraphicsObject() = %p\n", this, mGraphicsTexture.get());
195
196     return mGraphicsTexture.get();
197   }
198 }
199
200 void Texture::Create(Graphics::TextureUsageFlags usage)
201 {
202   DALI_ASSERT_ALWAYS(mResourceId == 0u);
203
204   Create(usage, Graphics::TextureAllocationPolicy::CREATION);
205 }
206
207 void Texture::Create(Graphics::TextureUsageFlags usage, Graphics::TextureAllocationPolicy allocationPolicy)
208 {
209   CreateWithData(usage, allocationPolicy, nullptr, 0u);
210 }
211
212 void Texture::CreateWithData(Graphics::TextureUsageFlags usage, Graphics::TextureAllocationPolicy allocationPolicy, uint8_t* data, uint32_t size)
213 {
214   auto createInfo = Graphics::TextureCreateInfo();
215   createInfo
216     .SetTextureType(Dali::Graphics::ConvertTextureType(mType))
217     .SetUsageFlags(usage)
218     .SetFormat(Dali::Graphics::ConvertPixelFormat(mPixelFormat))
219     .SetSize({mWidth, mHeight})
220     .SetLayout(Graphics::TextureLayout::LINEAR)
221     .SetAllocationPolicy(allocationPolicy)
222     .SetData(data)
223     .SetDataSize(size)
224     .SetNativeImage(mNativeImage)
225     .SetMipMapFlag(Graphics::TextureMipMapFlag::DISABLED);
226
227   mGraphicsTexture = mGraphicsController->CreateTexture(createInfo, std::move(mGraphicsTexture));
228 }
229
230 void Texture::Upload(PixelDataPtr pixelData, const Graphics::UploadParams& params)
231 {
232   DALI_ASSERT_ALWAYS(!mNativeImage);
233   DALI_ASSERT_ALWAYS(mResourceId == 0u);
234
235   const uint32_t srcStride = pixelData->GetStride();
236   uint32_t       srcOffset = 0u;
237   uint32_t       srcSize   = pixelData->GetBufferSize();
238
239   // Cache uploaded data
240   const auto uploadedDataWidth   = params.dataWidth;
241   const auto uploadedDataHeight  = params.dataHeight;
242   const auto uploadedPixelFormat = pixelData->GetPixelFormat();
243
244   const bool requiredSubPixelData = (!Pixel::IsCompressed(uploadedPixelFormat)) &&
245                                     ((params.dataXOffset != 0) ||
246                                      (params.dataYOffset != 0) ||
247                                      (uploadedDataWidth != pixelData->GetWidth()) ||
248                                      (uploadedDataHeight != pixelData->GetHeight()));
249
250   if(requiredSubPixelData)
251   {
252     /**
253      * TextureUpdateInfo use byte scaled offset / size.
254      *
255      * To make we only use sub-data of inputed PixelData, make srcOffset as 'start of SubPixelData.
256      *
257      *   |---- dataStrideByte -----|
258      *   |-----| <-- dataXOffsetByte
259      *   ...........................
260      *   ......A-----------+........
261      *   ......|           |........
262      *   ......|           |........
263      *   ......+-----------+C.......
264      *   ......B....................
265      *
266      * A) Start of SubPixelData. offsetByte = dataStrideByte * dataYOffset + dataXOffsetByte.
267      * B) offsetByte = A).offsetByte + dataStrideByte * dataHeight. Note, It can be out of original PixelData boundary.
268      * C) End of SubPixelData. offsetByte = B).offsetByte - dataStrideByte + dataWidthByte.
269      *
270      * srcOffset = A).offsetByte;
271      * srcSize = ( C).offsetByte - A).offsetByte );
272      */
273     const uint32_t bytePerPixel    = Pixel::GetBytesPerPixel(uploadedPixelFormat);
274     const uint32_t dataStrideByte  = (srcStride ? srcStride : pixelData->GetWidth()) * bytePerPixel;
275     const uint32_t dataXOffsetByte = params.dataXOffset * bytePerPixel;
276     const uint32_t dataWidthByte   = static_cast<uint32_t>(uploadedDataWidth) * bytePerPixel;
277
278     srcOffset = params.dataYOffset * dataStrideByte + dataXOffsetByte;
279     srcSize   = static_cast<uint32_t>(uploadedDataHeight) * dataStrideByte - (dataStrideByte - dataWidthByte);
280   }
281
282   // Update render texture value as uploaded data.
283   if(mUseUploadedParameter)
284   {
285     mWidth       = params.xOffset + uploadedDataWidth;
286     mHeight      = params.yOffset + uploadedDataHeight;
287     mPixelFormat = uploadedPixelFormat;
288   }
289
290   // Always create new graphics texture object if we use uploaded parameter as texture.
291   if(!mGraphicsTexture || mUseUploadedParameter)
292   {
293     const bool isSubImage(params.xOffset != 0u || params.yOffset != 0u ||
294                           uploadedDataWidth != (mWidth >> params.mipmap) ||
295                           uploadedDataHeight != (mHeight >> params.mipmap));
296     Create(static_cast<Graphics::TextureUsageFlags>(Graphics::TextureUsageFlagBits::SAMPLE), isSubImage ? Graphics::TextureAllocationPolicy::CREATION : Graphics::TextureAllocationPolicy::UPLOAD);
297   }
298
299   Graphics::TextureUpdateInfo info{};
300
301   info.dstTexture   = mGraphicsTexture.get();
302   info.dstOffset2D  = {params.xOffset, params.yOffset};
303   info.layer        = params.layer;
304   info.level        = params.mipmap;
305   info.srcReference = 0;
306   info.srcExtent2D  = {uploadedDataWidth, uploadedDataHeight};
307   info.srcOffset    = srcOffset;
308   info.srcSize      = srcSize;
309   info.srcStride    = srcStride;
310   info.srcFormat    = Dali::Graphics::ConvertPixelFormat(uploadedPixelFormat);
311
312   mUpdatedArea = Rect<uint16_t>(params.xOffset, params.yOffset, params.width, params.height);
313
314   Graphics::TextureUpdateSourceInfo updateSourceInfo{};
315   updateSourceInfo.sourceType                = Graphics::TextureUpdateSourceInfo::Type::PIXEL_DATA;
316   updateSourceInfo.pixelDataSource.pixelData = Dali::PixelData(pixelData.Get());
317
318   mGraphicsController->UpdateTextures({info}, {updateSourceInfo});
319
320   SetUpdated(true);
321 }
322
323 bool Texture::HasAlphaChannel() const
324 {
325   bool alpha = mHasAlpha;
326   if(mNativeImage)
327   {
328     alpha = mNativeImage->RequiresBlending();
329   }
330   return alpha;
331 }
332
333 bool Texture::IsGraphicsObjectChanged()
334 {
335   return mLatestUsedGraphicsTexture != GetGraphicsObject();
336 }
337
338 void Texture::NotifyTextureUpdated()
339 {
340   if(mRenderManager)
341   {
342     mRenderManager->SetTextureUpdated(TextureKey(GetTextureMemoryPool().GetKeyFromPtr(this)));
343   }
344 }
345
346 void Texture::GenerateMipmaps()
347 {
348   DALI_ASSERT_ALWAYS(mResourceId == 0u);
349
350   // Compressed pixel doesn't support mipmap generation.
351   if(Pixel::IsCompressed(mPixelFormat))
352   {
353     return;
354   }
355
356   if(!mGraphicsTexture)
357   {
358     Create(static_cast<Graphics::TextureUsageFlags>(Graphics::TextureUsageFlagBits::SAMPLE));
359   }
360
361   mGraphicsController->GenerateTextureMipmaps(*mGraphicsTexture.get());
362 }
363
364 void Texture::OnRenderFinished()
365 {
366   SetUpdated(false);
367
368   if(mResourceId != 0u)
369   {
370     mLatestUsedGraphicsTexture = GetGraphicsObject();
371     if(mLatestUsedGraphicsTexture != nullptr)
372     {
373       // We don't need to keep mResourceId anymore.
374       mResourceId = 0u;
375     }
376   }
377
378   mUpdatedArea = Rect<uint16_t>{0, 0, 0, 0};
379 }
380
381 Rect<uint16_t> Texture::GetUpdatedArea()
382 {
383   if(mNativeImage)
384   {
385     Rect<uint32_t> rect = mNativeImage->GetUpdatedArea();
386     mUpdatedArea.x      = static_cast<uint16_t>(rect.x);
387     mUpdatedArea.y      = static_cast<uint16_t>(rect.y);
388     mUpdatedArea.width  = static_cast<uint16_t>(rect.width);
389     mUpdatedArea.height = static_cast<uint16_t>(rect.height);
390   }
391   return mUpdatedArea;
392 }
393
394 } // namespace Render
395
396 } // namespace Internal
397
398 } // namespace Dali