Distinguish NativeImage from Image & Clean PixelFormat from ImageAttribute and Texture
[platform/core/uifw/dali-core.git] / dali / internal / render / gl-resources / bitmap-texture.cpp
1 /*
2  * Copyright (c) 2014 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 <dali/internal/render/gl-resources/bitmap-texture.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/internal/render/common/vertex.h>
24 #include <dali/internal/render/common/performance-monitor.h>
25 #include <dali/internal/render/gl-resources/context.h>
26 #include <dali/internal/render/gl-resources/texture-units.h>
27
28 namespace Dali
29 {
30
31 namespace Internal
32 {
33
34 BitmapTexture::BitmapTexture(
35   Integration::Bitmap* const bitmap,
36   const Integration::Bitmap::PackedPixelsProfile * const bitmapPackedPixelsProfile,
37   Context& context,
38   ResourcePolicy::Discardable policy)
39 : Texture( context,
40            bitmapPackedPixelsProfile->GetBufferWidth(),
41            bitmapPackedPixelsProfile->GetBufferHeight(),
42            bitmap->GetImageWidth(),
43            bitmap->GetImageHeight()),
44   mBitmap(bitmap),
45   mClearPixels(false),
46   mDiscardPolicy(policy),
47   mPixelFormat(bitmap->GetPixelFormat())
48 {
49   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
50   DALI_LOG_SET_OBJECT_STRING(this, DALI_LOG_GET_OBJECT_STRING(bitmap));
51 }
52
53 BitmapTexture::BitmapTexture(
54   unsigned int width,
55   unsigned int height,
56   Pixel::Format pixelFormat,
57   bool clearPixels,
58   Context& context,
59   ResourcePolicy::Discardable policy)
60 : Texture( context,
61            width, height,
62            width, height),
63   mBitmap(NULL),
64   mClearPixels(clearPixels),
65   mDiscardPolicy(policy),
66   mPixelFormat( pixelFormat )
67 {
68   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
69 }
70
71 BitmapTexture::~BitmapTexture()
72 {
73   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
74
75   // GlCleanup() should already have been called by TextureCache ensuring the resource is destroyed
76   // on the render thread. (And avoiding a potentially problematic virtual call in the destructor)
77 }
78
79 void BitmapTexture::UploadBitmapArray( const BitmapUploadArray& bitmapArray )
80 {
81   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
82
83   if( mId == 0 )
84   {
85     CreateGlTexture();
86   }
87
88   mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
89   mContext.Bind2dTexture(mId);
90   mContext.PixelStorei(GL_UNPACK_ALIGNMENT, 1); // We always use tightly packed data
91
92   GLenum pixelFormat   = GL_RGBA;
93   GLenum pixelDataType = GL_UNSIGNED_BYTE;
94
95   Integration::ConvertToGlFormat(mPixelFormat, pixelDataType, pixelFormat);
96
97   // go through each bitmap uploading it
98
99   for( BitmapUploadArray::const_iterator iter =  bitmapArray.begin(), endIter = bitmapArray.end(); iter != endIter ; ++iter)
100   {
101     const BitmapUpload& bitmapItem((*iter));
102
103     DALI_ASSERT_ALWAYS(bitmapItem.mPixelData);
104
105     const unsigned char* pixels = bitmapItem.mPixelData;
106
107     DALI_ASSERT_DEBUG( (pixels!=NULL) && "bitmap has no data \n");
108
109     unsigned int bitmapWidth(bitmapItem.mWidth);
110     unsigned int bitmapHeight(bitmapItem.mHeight);
111
112     DALI_LOG_INFO(Debug::Filter::gImage, Debug::General, "upload bitmap to texture :%d y:%d w:%d h:%d\n",
113                             bitmapItem.mXpos,
114                             bitmapItem.mYpos,
115                             bitmapWidth,
116                             bitmapHeight);
117
118     mContext.TexSubImage2D(GL_TEXTURE_2D,
119                            0,                   /* mip map level */
120                            bitmapItem.mXpos,    /* X pos */
121                            bitmapItem.mYpos,    /* Y pos */
122                            bitmapWidth,         /* width */
123                            bitmapHeight,        /* height */
124                            pixelFormat,         /* our bitmap format (should match internal format) */
125                            pixelDataType,       /* pixel data type */
126                            pixels);             /* texture data */
127
128     if( BitmapUpload::DISCARD_PIXEL_DATA == bitmapItem.mDiscard)
129     {
130       delete [] bitmapItem.mPixelData;
131     }
132   }
133 }
134
135 bool BitmapTexture::HasAlphaChannel() const
136 {
137   return Pixel::HasAlpha(mPixelFormat);
138 }
139
140 bool BitmapTexture::IsFullyOpaque() const
141 {
142   if( mBitmap )
143   {
144     return mBitmap->IsFullyOpaque();
145   }
146   else
147   {
148     return ! HasAlphaChannel(); // Todo: amalgamate updated bitmap's IsFullyOpaque()
149   }
150 }
151
152 // Bitmap buffer has been changed. Upload changes to GPU.
153 void BitmapTexture::AreaUpdated( const RectArea& updateArea, const unsigned char* pixels )
154 {
155   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
156   DALI_LOG_INFO(Debug::Filter::gGLResource, Debug::Verbose, "BitmapTexture::AreaUpdated()\n");
157
158   GLenum pixelFormat   = GL_RGBA;
159   GLenum pixelDataType = GL_UNSIGNED_BYTE;
160   Integration::ConvertToGlFormat(mPixelFormat, pixelDataType, pixelFormat);
161
162   mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
163
164   mContext.Bind2dTexture(mId);
165
166   if( ! updateArea.IsEmpty() )
167   {
168     mContext.PixelStorei( GL_UNPACK_ALIGNMENT, 1 ); // We always use tightly packed data
169     DALI_LOG_INFO( Debug::Filter::gImage, Debug::General, "Update x:%d y:%d w:%d h:%d\n",
170                    updateArea.x, updateArea.y, updateArea.width ,updateArea.height );
171
172     const unsigned int pitchPixels = mWidth;
173     const unsigned int pixelDepth = GetBytesPerPixel( mPixelFormat );
174
175     // If the width of the source update area is the same as the pitch, then can
176     // copy the contents in a single contiguous TexSubImage call.
177     if(updateArea.x == 0 && updateArea.width == pitchPixels)
178     {
179       pixels += updateArea.y * pitchPixels * pixelDepth;
180       mContext.TexSubImage2D( GL_TEXTURE_2D,0, updateArea.x, updateArea.y,
181                               updateArea.width, updateArea.height,
182                               pixelFormat, pixelDataType, pixels );
183     }
184     else
185     {
186       // Otherwise the source buffer needs to be copied line at a time, as OpenGL ES
187       // does not support source strides. (no GL_UNPACK_ROW_LENGTH supported)
188       unsigned int yBottom = updateArea.y + updateArea.height;
189       pixels += (updateArea.y * pitchPixels + updateArea.x) * pixelDepth;
190
191       for(unsigned int y = updateArea.y; y < yBottom; y++)
192       {
193         mContext.TexSubImage2D( GL_TEXTURE_2D,0, updateArea.x, y,
194                                 updateArea.width, 1,
195                                 pixelFormat, pixelDataType, pixels );
196         pixels += pitchPixels * pixelDepth;
197       }
198     }
199
200     INCREASE_BY( PerformanceMonitor::TEXTURE_DATA_UPLOADED,
201                  updateArea.Area()* GetBytesPerPixel( mPixelFormat ));
202   }
203 }
204
205 void BitmapTexture::AssignBitmap( bool generateTexture, const unsigned char* pixels )
206 {
207   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
208   DALI_LOG_INFO(Debug::Filter::gGLResource, Debug::Verbose, "BitmapTexture::AssignBitmap()\n");
209
210   GLenum pixelFormat = GL_RGBA;
211   GLenum pixelDataType = GL_UNSIGNED_BYTE;
212
213   if( generateTexture )
214   {
215     mContext.GenTextures(1, &mId);
216   }
217   DALI_ASSERT_DEBUG( mId != 0 );
218
219   mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
220   mContext.Bind2dTexture(mId);
221   Integration::ConvertToGlFormat(mPixelFormat, pixelDataType, pixelFormat);
222
223   mContext.PixelStorei(GL_UNPACK_ALIGNMENT, 1); // We always use tightly packed data
224   mContext.TexImage2D(GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, pixels);
225   mContext.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
226   mContext.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
227
228   INCREASE_BY( PerformanceMonitor::TEXTURE_DATA_UPLOADED, GetBytesPerPixel(mPixelFormat) * mWidth * mHeight );
229 }
230
231 void BitmapTexture::Update( Integration::Bitmap* bitmap )
232 {
233   DALI_LOG_INFO( Debug::Filter::gGLResource, Debug::General, "BitmapTexture::Update(bitmap:%p )\n", bitmap );
234   DALI_ASSERT_DEBUG( bitmap != 0 );
235   if( !bitmap )
236   {
237     DALI_LOG_ERROR( "Passed a null bitmap to update this bitmap texture." );
238     return;
239   }
240
241   // Only Packed-pixel bitmaps are ever associated with BitmapTextures, so we should never be passed any other kind:
242   const Integration::Bitmap::PackedPixelsProfile * const bitmapPackedPixels = bitmap->GetPackedPixelsProfile();
243   DALI_ASSERT_DEBUG(bitmapPackedPixels);
244   if( !bitmapPackedPixels )
245   {
246     ///! This should never happen.
247     DALI_LOG_ERROR("Passed an incompatible bitmap type to update this bitmap texture.");
248     return;
249   }
250   mBitmap = bitmap;
251
252   const unsigned char* pixels = mBitmap->GetBuffer();
253
254   // We should never have null pixel data here - resource manager has deliberately loaded/reloaded data
255
256   DALI_ASSERT_DEBUG( pixels != NULL );
257
258   if( NULL == pixels )
259   {
260     DALI_LOG_ERROR("BitmapTexture::Upload() - Bitmap has no pixel data.\n");
261   }
262   else if( mId != 0 )
263   {
264     if( mImageWidth == mBitmap->GetImageWidth() &&
265         mImageHeight == mBitmap->GetImageHeight() &&
266         mWidth  == bitmapPackedPixels->GetBufferWidth() &&
267         mHeight == bitmapPackedPixels->GetBufferHeight() &&
268         mPixelFormat == mBitmap->GetPixelFormat() ) // and size hasn't changed
269     {
270       RectArea area(0, 0, mImageWidth, mImageHeight);  // just update whole texture
271       AreaUpdated( area, pixels );
272       DiscardBitmapBuffer();
273     }
274     else // Otherwise, reload the pixel data
275     {
276       mImageWidth  = mBitmap->GetImageWidth();
277       mImageHeight = mBitmap->GetImageHeight();
278       mWidth       = bitmapPackedPixels->GetBufferWidth();
279       mHeight      = bitmapPackedPixels->GetBufferHeight();
280       mPixelFormat = mBitmap->GetPixelFormat();
281
282       AssignBitmap( false, pixels );
283     }
284   }
285 }
286
287 void BitmapTexture::Update( Integration::Bitmap* srcBitmap, std::size_t xOffset, std::size_t yOffset )
288 {
289   if( NULL != srcBitmap )
290   {
291     GLenum pixelFormat   = GL_RGBA;
292     GLenum pixelDataType = GL_UNSIGNED_BYTE;
293     Integration::ConvertToGlFormat( mPixelFormat, pixelDataType, pixelFormat );
294
295     if( !mId )
296     {
297       mContext.GenTextures( 1, &mId );
298
299       mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
300       mContext.Bind2dTexture( mId );
301       mContext.PixelStorei( GL_UNPACK_ALIGNMENT, 1 );
302
303       mContext.TexImage2D( GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, NULL );
304       mContext.TexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
305       mContext.TexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
306     }
307     else
308     {
309       mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
310       mContext.Bind2dTexture( mId );
311       mContext.PixelStorei( GL_UNPACK_ALIGNMENT, 1 );
312     }
313
314     mContext.TexSubImage2D( GL_TEXTURE_2D, 0,
315                             xOffset, yOffset,
316                             srcBitmap->GetImageWidth(), srcBitmap->GetImageHeight(),
317                             pixelFormat, pixelDataType, srcBitmap->GetBuffer() );
318   }
319 }
320
321 void BitmapTexture::UpdateArea( const RectArea& updateArea )
322 {
323   DALI_LOG_INFO(Debug::Filter::gGLResource, Debug::General, "BitmapTexture::UpdateArea()\n");
324
325   if( mBitmap != 0 )
326   {
327     const unsigned char* pixels = mBitmap->GetBuffer();
328
329     // Pixel data could be null if we've uploaded to GL and discarded the data.
330
331     if( NULL != pixels )
332     {
333       if( mId ) // If the texture is already bound
334       {
335         if( updateArea.IsEmpty() )
336         {
337           RectArea area;
338           area.x = 0;
339           area.y = 0;
340           area.width = mImageWidth;
341           area.height = mImageHeight;
342           AreaUpdated( area, pixels );
343         }
344         else
345         {
346           AreaUpdated( updateArea, pixels );
347         }
348       }
349     }
350   }
351 }
352
353 void BitmapTexture::ClearAreas( const BitmapClearArray& areaArray, std::size_t blockSize, uint32_t color )
354 {
355   if(mId > 0)
356   {
357     DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
358     DALI_LOG_INFO(Debug::Filter::gGLResource, Debug::Verbose, "BitmapTexture::AreaUpdated()\n");
359
360     GLenum pixelFormat   = GL_RGBA;
361     GLenum pixelDataType = GL_UNSIGNED_BYTE;
362     Integration::ConvertToGlFormat(mPixelFormat, pixelDataType, pixelFormat);
363
364     mContext.ActiveTexture( TEXTURE_UNIT_UPLOAD );
365     mContext.Bind2dTexture(mId);
366
367     size_t numPixels = blockSize*blockSize;
368     size_t bytesPerPixel = Pixel::GetBytesPerPixel(mPixelFormat);
369     char* clearPixels = (char*)malloc(numPixels * bytesPerPixel);
370
371     for(size_t i=0; i<numPixels; i++)
372     {
373       memcpy(&clearPixels[i*bytesPerPixel], &color, bytesPerPixel);
374     }
375
376     for( BitmapClearArray::const_iterator iter =  areaArray.begin(), endIter = areaArray.end(); iter != endIter ; ++iter)
377     {
378       const Vector2& clearPos((*iter));
379
380       mContext.PixelStorei( GL_UNPACK_ALIGNMENT, 1 ); // We always use tightly packed data
381       DALI_LOG_INFO( Debug::Filter::gImage, Debug::General, "Update x:%0.2f y:%0.2f w:%d h:%d\n",
382                      clearPos.x, clearPos.y, blockSize, blockSize );
383
384       mContext.TexSubImage2D(GL_TEXTURE_2D,
385                              0,
386                              clearPos.x,
387                              clearPos.y,
388                              blockSize,
389                              blockSize,
390                              pixelFormat,         /* our bitmap format (should match internal format) */
391                              pixelDataType,       /* pixel data type */
392                              clearPixels);        /* texture data */
393
394       INCREASE_BY( PerformanceMonitor::TEXTURE_DATA_UPLOADED, numPixels * bytesPerPixel );
395     }
396     free(clearPixels);
397   }
398 }
399
400 bool BitmapTexture::UpdateOnCreate()
401 {
402   return true;
403 }
404
405 bool BitmapTexture::CreateGlTexture()
406 {
407   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
408   DALI_LOG_INFO(Debug::Filter::gImage, Debug::Verbose, "BitmapTexture::CreateGlTexture() Bitmap: %s\n", DALI_LOG_GET_OBJECT_C_STR(this));
409
410   if( mBitmap )
411   {
412     const unsigned char* pixels = mBitmap->GetBuffer();
413
414     // pixel data could be NULL here if we've had a context loss and we previously discarded
415     // the pixel data on the previous upload. If it is null, then we shouldn't generate a
416     // new GL Texture; leaving mId as zero. Eventually, the bitmap will get reloaded,
417     // and pixels will become non-null.
418
419     if( NULL != pixels )
420     {
421       AssignBitmap( true, pixels );
422       DiscardBitmapBuffer();
423     }
424   }
425   else
426   {
427     const unsigned char* pixels = NULL;
428     std::vector<unsigned char> pixelData;
429     if( ( NULL == pixels ) && ( true == mClearPixels ) )
430     {
431       unsigned int size = mWidth * mHeight * Pixel::GetBytesPerPixel(mPixelFormat);
432       pixelData.resize(size, 0);
433       pixels = &pixelData[0];
434     }
435     AssignBitmap( true, pixels );
436   }
437
438   return mId != 0;
439 }
440
441 bool BitmapTexture::Init()
442 {
443   DALI_LOG_TRACE_METHOD(Debug::Filter::gImage);
444   // mBitmap should be initialized by now
445   return (mBitmap != 0);
446 }
447
448 unsigned int BitmapTexture::GetWidth() const
449 {
450   unsigned int width = mWidth;
451   if( mBitmap )
452   {
453     width = mBitmap->GetImageWidth();
454   }
455   return width;
456 }
457
458 unsigned int BitmapTexture::GetHeight() const
459 {
460   unsigned int height = mHeight;
461   if( mBitmap )
462   {
463     height = mBitmap->GetImageHeight();
464   }
465   return height;
466 }
467
468 void BitmapTexture::DiscardBitmapBuffer()
469 {
470   DALI_LOG_INFO(Debug::Filter::gImage, Debug::General, "BitmapTexture::DiscardBitmapBuffer() DiscardPolicy: %s\n", mDiscardPolicy == ResourcePolicy::DISCARD?"DISCARD":"RETAIN");
471
472   if( ResourcePolicy::DISCARD == mDiscardPolicy )
473   {
474     DALI_LOG_INFO(Debug::Filter::gImage, Debug::General, "  Discarding bitmap\n");
475     mBitmap->DiscardBuffer();
476   }
477 }
478
479
480 } //namespace Internal
481
482 } //namespace Dali