Apply EncodedImageBuffer with Atlas
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / image-loader / image-atlas-impl.cpp
1 /*
2  * Copyright (c) 2022 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 // CLASS HEADER
19 #include "image-atlas-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/image-loading.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/public-api/signals/callback.h>
25 #include <string.h>
26
27 // INTERNAL HEADERS
28 #include <dali-toolkit/internal/image-loader/async-image-loader-impl.h>
29
30 namespace Dali
31 {
32 namespace Toolkit
33 {
34 namespace Internal
35 {
36 Texture ImageAtlas::PackToAtlas(const std::vector<PixelData>& pixelData, Dali::Vector<Vector4>& textureRects)
37 {
38   // Record each block size
39   Dali::Vector<Uint16Pair> blockSizes;
40   SizeType                 count = pixelData.size();
41   for(SizeType index = 0; index < count; index++)
42   {
43     blockSizes.PushBack(ImageDimensions(pixelData[index].GetWidth(), pixelData[index].GetHeight()));
44   }
45
46   // Ask atlasPacker for packing position of each block
47   Dali::Vector<Uint16Pair> packPositions;
48   ImageDimensions          atlasSize = AtlasPacker::GroupPack(blockSizes, packPositions);
49
50   // Prepare for outout texture rect array
51   textureRects.Clear();
52   textureRects.Resize(count);
53
54   // create the texture for uploading the multiple pixel data
55   Texture atlasTexture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, atlasSize.GetWidth(), atlasSize.GetHeight());
56
57   float atlasWidth  = static_cast<float>(atlasTexture.GetWidth());
58   float atlasHeight = static_cast<float>(atlasTexture.GetHeight());
59   int   packPositionX, packPositionY;
60   // Upload the pixel data one by one to its packing position, and record the texture rects
61   for(SizeType index = 0; index < count; index++)
62   {
63     packPositionX = packPositions[index].GetX();
64     packPositionY = packPositions[index].GetY();
65     atlasTexture.Upload(pixelData[index], 0u, 0u, packPositionX, packPositionY, pixelData[index].GetWidth(), pixelData[index].GetHeight());
66
67     // Apply the half pixel correction to avoid the color bleeding between neighbour blocks
68     textureRects[index].x = (static_cast<float>(packPositionX) + 0.5f) / atlasWidth;                                 // left
69     textureRects[index].y = (static_cast<float>(packPositionY) + 0.5f) / atlasHeight;                                // top
70     textureRects[index].z = (static_cast<float>(packPositionX + pixelData[index].GetWidth()) - 0.5f) / atlasWidth;   // right
71     textureRects[index].w = (static_cast<float>(packPositionY + pixelData[index].GetHeight()) - 0.5f) / atlasHeight; // bottom
72   }
73
74   return atlasTexture;
75 }
76
77 ImageAtlas::ImageAtlas(SizeType width, SizeType height, Pixel::Format pixelFormat)
78 : mAtlas(Texture::New(Dali::TextureType::TEXTURE_2D, pixelFormat, width, height)),
79   mPacker(width, height),
80   mAsyncLoader(Toolkit::AsyncImageLoader::New()),
81   mBrokenImageUrl(""),
82   mBrokenImageSize(),
83   mWidth(static_cast<float>(width)),
84   mHeight(static_cast<float>(height)),
85   mPixelFormat(pixelFormat)
86 {
87   mAsyncLoader.ImageLoadedSignal().Connect(this, &ImageAtlas::UploadToAtlas);
88 }
89
90 ImageAtlas::~ImageAtlas()
91 {
92   const std::size_t count = mLoadingTaskInfoContainer.Count();
93   for(std::size_t i = 0; i < count; ++i)
94   {
95     // Call unregister to every observer in the list.
96     // Note that, the Atlas can be registered to same observer multiple times, and the Unregister method only remove one item each time.
97     // In this way, the atlas is actually detached from a observer either every upload call invoked by this observer is completed or atlas is destroyed.
98     if(mLoadingTaskInfoContainer[i]->observer)
99     {
100       mLoadingTaskInfoContainer[i]->observer->Unregister(*this);
101     }
102   }
103
104   mLoadingTaskInfoContainer.Clear();
105 }
106
107 IntrusivePtr<ImageAtlas> ImageAtlas::New(SizeType width, SizeType height, Pixel::Format pixelFormat)
108 {
109   IntrusivePtr<ImageAtlas> internal = new ImageAtlas(width, height, pixelFormat);
110
111   return internal;
112 }
113
114 Texture ImageAtlas::GetAtlas()
115 {
116   return mAtlas;
117 }
118
119 float ImageAtlas::GetOccupancyRate() const
120 {
121   return 1.f - static_cast<float>(mPacker.GetAvailableArea()) / (mWidth * mHeight);
122 }
123
124 void ImageAtlas::SetBrokenImage(const std::string& brokenImageUrl)
125 {
126   mBrokenImageSize = Dali::GetClosestImageSize(brokenImageUrl);
127   if(mBrokenImageSize.GetWidth() > 0 && mBrokenImageSize.GetHeight() > 0) // check the url is valid
128   {
129     mBrokenImageUrl = brokenImageUrl;
130   }
131 }
132
133 bool ImageAtlas::Upload(Vector4&             textureRect,
134                         const VisualUrl&     url,
135                         ImageDimensions      size,
136                         FittingMode::Type    fittingMode,
137                         bool                 orientationCorrection,
138                         AtlasUploadObserver* atlasUploadObserver)
139 {
140   ImageDimensions dimensions = size;
141   ImageDimensions zero;
142   if(size == zero) // image size not provided
143   {
144     dimensions = Dali::GetClosestImageSize(url.GetUrl());
145     if(dimensions == zero) // Fail to read the image & broken image file exists
146     {
147       if(!mBrokenImageUrl.empty())
148       {
149         return Upload(textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver);
150       }
151       else
152       {
153         textureRect = Vector4::ZERO;
154         return true;
155       }
156     }
157   }
158
159   uint32_t packPositionX = 0;
160   uint32_t packPositionY = 0;
161   if(mPacker.Pack(dimensions.GetWidth(), dimensions.GetHeight(), packPositionX, packPositionY))
162   {
163     uint32_t loadId = GetImplementation(mAsyncLoader).Load(url, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad::OFF);
164     mLoadingTaskInfoContainer.PushBack(new LoadingTaskInfo(loadId, packPositionX, packPositionY, dimensions.GetWidth(), dimensions.GetHeight(), atlasUploadObserver));
165     // apply the half pixel correction
166     textureRect.x = (static_cast<float>(packPositionX) + 0.5f) / mWidth;                      // left
167     textureRect.y = (static_cast<float>(packPositionY) + 0.5f) / mHeight;                     // top
168     textureRect.z = (static_cast<float>(packPositionX + dimensions.GetX()) - 0.5f) / mWidth;  // right
169     textureRect.w = (static_cast<float>(packPositionY + dimensions.GetY()) - 0.5f) / mHeight; // bottom
170
171     if(atlasUploadObserver)
172     {
173       // register to the observer,
174       // Not that a matching unregister call should be invoked in UploadToAtlas if the observer is still alive by then.
175       atlasUploadObserver->Register(*this);
176     }
177
178     return true;
179   }
180
181   return false;
182 }
183
184 bool ImageAtlas::Upload(Vector4&                  textureRect,
185                         const EncodedImageBuffer& encodedImageBuffer,
186                         ImageDimensions           size,
187                         FittingMode::Type         fittingMode,
188                         bool                      orientationCorrection,
189                         AtlasUploadObserver*      atlasUploadObserver)
190 {
191   ImageDimensions zero;
192   if(size == zero) // image size not provided
193   {
194     DALI_LOG_ERROR("Desired size is zero! We need to setup desired size for Atlas.\n");
195     // EncodedImageBuffer didn't support to get closest image size.
196     // Just draw broken image.
197     if(!mBrokenImageUrl.empty())
198     {
199       return Upload(textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver);
200     }
201     else
202     {
203       textureRect = Vector4::ZERO;
204       return true;
205     }
206   }
207
208   uint32_t packPositionX = 0;
209   uint32_t packPositionY = 0;
210   if(mPacker.Pack(size.GetWidth(), size.GetHeight(), packPositionX, packPositionY))
211   {
212     uint32_t loadId = GetImplementation(mAsyncLoader).LoadEncodedImageBuffer(encodedImageBuffer, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad::OFF);
213     mLoadingTaskInfoContainer.PushBack(new LoadingTaskInfo(loadId, packPositionX, packPositionY, size.GetWidth(), size.GetHeight(), atlasUploadObserver));
214     // apply the half pixel correction
215     textureRect.x = (static_cast<float>(packPositionX) + 0.5f) / mWidth;                // left
216     textureRect.y = (static_cast<float>(packPositionY) + 0.5f) / mHeight;               // top
217     textureRect.z = (static_cast<float>(packPositionX + size.GetX()) - 0.5f) / mWidth;  // right
218     textureRect.w = (static_cast<float>(packPositionY + size.GetY()) - 0.5f) / mHeight; // bottom
219
220     if(atlasUploadObserver)
221     {
222       // register to the observer,
223       // Not that a matching unregister call should be invoked in UploadToAtlas if the observer is still alive by then.
224       atlasUploadObserver->Register(*this);
225     }
226
227     return true;
228   }
229
230   return false;
231 }
232
233 bool ImageAtlas::Upload(Vector4& textureRect, PixelData pixelData)
234 {
235   uint32_t packPositionX = 0;
236   uint32_t packPositionY = 0;
237   if(mPacker.Pack(pixelData.GetWidth(), pixelData.GetHeight(), packPositionX, packPositionY))
238   {
239     mAtlas.Upload(pixelData, 0u, 0u, packPositionX, packPositionY, pixelData.GetWidth(), pixelData.GetHeight());
240
241     // apply the half pixel correction
242     textureRect.x = (static_cast<float>(packPositionX) + 0.5f) / mWidth;                          // left
243     textureRect.y = (static_cast<float>(packPositionY) + 0.5f) / mHeight;                         // top
244     textureRect.z = (static_cast<float>(packPositionX + pixelData.GetWidth()) - 0.5f) / mWidth;   // right
245     textureRect.w = (static_cast<float>(packPositionY + pixelData.GetHeight()) - 0.5f) / mHeight; // bottom
246
247     return true;
248   }
249
250   return false;
251 }
252
253 void ImageAtlas::Remove(const Vector4& textureRect)
254 {
255   mPacker.DeleteBlock(static_cast<SizeType>(textureRect.x * mWidth),
256                       static_cast<SizeType>(textureRect.y * mHeight),
257                       static_cast<SizeType>((textureRect.z - textureRect.x) * mWidth + 1.f),
258                       static_cast<SizeType>((textureRect.w - textureRect.y) * mHeight + 1.f));
259 }
260
261 void ImageAtlas::ObserverDestroyed(AtlasUploadObserver* observer)
262 {
263   const std::size_t count = mLoadingTaskInfoContainer.Count();
264   for(std::size_t i = 0; i < count; ++i)
265   {
266     if(mLoadingTaskInfoContainer[i]->observer == observer)
267     {
268       // the observer is destructing, so its member function should not be called anymore
269       mLoadingTaskInfoContainer[i]->observer = NULL;
270     }
271   }
272 }
273
274 void ImageAtlas::UploadToAtlas(uint32_t id, PixelData pixelData)
275 {
276   if(mLoadingTaskInfoContainer[0]->loadTaskId == id)
277   {
278     Rect<uint32_t> packRect(mLoadingTaskInfoContainer[0]->packRect);
279     if(!pixelData || (pixelData.GetWidth() == 0 && pixelData.GetHeight() == 0))
280     {
281       if(!mBrokenImageUrl.empty()) // replace with the broken image
282       {
283         UploadBrokenImage(packRect);
284       }
285     }
286     else
287     {
288       if(pixelData.GetWidth() < packRect.width || pixelData.GetHeight() < packRect.height)
289       {
290         DALI_LOG_ERROR("Can not upscale the image from actual loaded size [ %d, %d ] to specified size [ %d, %d ]\n",
291                        pixelData.GetWidth(),
292                        pixelData.GetHeight(),
293                        packRect.width,
294                        packRect.height);
295       }
296
297       mAtlas.Upload(pixelData, 0u, 0u, packRect.x, packRect.y, packRect.width, packRect.height);
298     }
299
300     if(mLoadingTaskInfoContainer[0]->observer)
301     {
302       mLoadingTaskInfoContainer[0]->observer->UploadCompleted();
303       mLoadingTaskInfoContainer[0]->observer->Unregister(*this);
304     }
305
306     mLoadingTaskInfoContainer.Erase(mLoadingTaskInfoContainer.Begin());
307   }
308 }
309
310 void ImageAtlas::UploadBrokenImage(const Rect<uint32_t>& area)
311 {
312   Devel::PixelBuffer brokenBuffer = LoadImageFromFile(mBrokenImageUrl, ImageDimensions(area.width, area.height));
313   SizeType           loadedWidth  = brokenBuffer.GetWidth();
314   SizeType           loadedHeight = brokenBuffer.GetHeight();
315
316   bool     needBackgroundClear = false;
317   SizeType packX               = area.x;
318   SizeType packY               = area.y;
319   // locate the broken image in the middle.
320   if(area.width > loadedWidth)
321   {
322     packX += (area.width - loadedWidth) / 2;
323     needBackgroundClear = true;
324   }
325   if(area.height > loadedHeight)
326   {
327     packY += (area.height - loadedHeight) / 2;
328     needBackgroundClear = true;
329   }
330
331   if(needBackgroundClear)
332   {
333     SizeType           size       = area.width * area.height * Pixel::GetBytesPerPixel(mPixelFormat);
334     Devel::PixelBuffer background = Devel::PixelBuffer::New(area.width, area.height, mPixelFormat);
335     unsigned char*     buffer     = background.GetBuffer();
336     for(SizeType idx = 0; idx < size; idx++)
337     {
338       buffer[idx] = 0x00;
339     }
340     PixelData pixelData = Devel::PixelBuffer::Convert(background);
341     mAtlas.Upload(pixelData, 0u, 0u, area.x, area.y, area.width, area.height);
342   }
343
344   PixelData brokenPixelData = Devel::PixelBuffer::Convert(brokenBuffer);
345   mAtlas.Upload(brokenPixelData, 0u, 0u, packX, packY, loadedWidth, loadedHeight);
346 }
347
348 } // namespace Internal
349
350 } // namespace Toolkit
351
352 } // namespace Dali