[dali_1.4.55] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / image / image-visual.cpp
1 /*
2  * Copyright (c) 2020 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-toolkit/internal/visuals/image/image-visual.h>
20
21 // EXTERNAL HEADERS
22 #include <cstring> // for strlen()
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/public-api/images/resource-image.h>
26 #include <dali/public-api/images/native-image.h>
27 #include <dali/devel-api/images/texture-set-image.h>
28 #include <dali/devel-api/adaptor-framework/image-loading.h>
29 #include <dali/devel-api/scripting/enum-helper.h>
30 #include <dali/devel-api/scripting/scripting.h>
31 #include <dali/integration-api/debug.h>
32
33 // INTERNAL HEADERS
34 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
35 #include <dali-toolkit/public-api/visuals/visual-properties.h>
36 #include <dali-toolkit/devel-api/visuals/image-visual-actions-devel.h>
37 #include <dali-toolkit/internal/visuals/texture-manager-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
40 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
41 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
42 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
43 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
44 #include <dali-toolkit/internal/visuals/visual-url.h>
45 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
46
47 namespace Dali
48 {
49
50 namespace Toolkit
51 {
52
53 namespace Internal
54 {
55
56 namespace
57 {
58
59 // property names
60 const char * const IMAGE_FITTING_MODE( "fittingMode" );
61 const char * const IMAGE_SAMPLING_MODE( "samplingMode" );
62 const char * const IMAGE_DESIRED_WIDTH( "desiredWidth" );
63 const char * const IMAGE_DESIRED_HEIGHT( "desiredHeight" );
64 const char * const SYNCHRONOUS_LOADING( "synchronousLoading" );
65 const char * const IMAGE_ATLASING("atlasing");
66 const char * const ALPHA_MASK_URL("alphaMaskUrl");
67
68 // fitting modes
69 DALI_ENUM_TO_STRING_TABLE_BEGIN( FITTING_MODE )
70 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SHRINK_TO_FIT )
71 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SCALE_TO_FILL )
72 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_WIDTH )
73 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_HEIGHT )
74 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, DEFAULT )
75 DALI_ENUM_TO_STRING_TABLE_END( FITTING_MODE )
76
77 // sampling modes
78 DALI_ENUM_TO_STRING_TABLE_BEGIN( SAMPLING_MODE )
79 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX )
80 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NEAREST )
81 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, LINEAR )
82 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_NEAREST )
83 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_LINEAR )
84 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NO_FILTER )
85 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, DONT_CARE )
86 DALI_ENUM_TO_STRING_TABLE_END( SAMPLING_MODE )
87
88 // wrap modes
89 DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE )
90 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT )
91 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE )
92 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT )
93 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT )
94 DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE )
95
96 // load policies
97 DALI_ENUM_TO_STRING_TABLE_BEGIN( LOAD_POLICY )
98 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE )
99 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED )
100 DALI_ENUM_TO_STRING_TABLE_END( LOAD_POLICY )
101
102 // release policies
103 DALI_ENUM_TO_STRING_TABLE_BEGIN( RELEASE_POLICY )
104 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED )
105 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED )
106 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER )
107 DALI_ENUM_TO_STRING_TABLE_END( RELEASE_POLICY )
108
109 const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
110
111 const char* DEFAULT_SAMPLER_TYPENAME = "sampler2D";
112
113 const float PIXEL_ALIGN_ON = 1.0f;
114 const float PIXEL_ALIGN_OFF = 0.0f;
115
116 Geometry CreateGeometry( VisualFactoryCache& factoryCache, ImageDimensions gridSize )
117 {
118   Geometry geometry;
119
120   if( gridSize == ImageDimensions( 1, 1 ) )
121   {
122     geometry = factoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
123   }
124   else
125   {
126     geometry = VisualFactoryCache::CreateGridGeometry( gridSize );
127   }
128
129   return geometry;
130 }
131
132 } // unnamed namespace
133
134 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
135                                  ImageVisualShaderFactory& shaderFactory,
136                                  const VisualUrl& imageUrl,
137                                  const Property::Map& properties,
138                                  ImageDimensions size,
139                                  FittingMode::Type fittingMode,
140                                  Dali::SamplingMode::Type samplingMode )
141 {
142   ImageVisualPtr imageVisualPtr( new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode ) );
143   imageVisualPtr->SetProperties( properties );
144   return imageVisualPtr;
145 }
146
147 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
148                                  ImageVisualShaderFactory& shaderFactory,
149                                  const VisualUrl& imageUrl,
150                                  ImageDimensions size,
151                                  FittingMode::Type fittingMode,
152                                  Dali::SamplingMode::Type samplingMode )
153 {
154   return new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode );
155 }
156
157 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Image& image )
158 {
159   return new ImageVisual( factoryCache, shaderFactory, image );
160 }
161
162 ImageVisual::ImageVisual( VisualFactoryCache& factoryCache,
163                           ImageVisualShaderFactory& shaderFactory,
164                           const VisualUrl& imageUrl,
165                           ImageDimensions size,
166                           FittingMode::Type fittingMode,
167                           Dali::SamplingMode::Type samplingMode )
168 : Visual::Base( factoryCache, Visual::FittingMode::FILL ),
169   mImage(),
170   mPixelArea( FULL_TEXTURE_RECT ),
171   mPlacementActor(),
172   mImageUrl( imageUrl ),
173   mMaskingData( ),
174   mDesiredSize( size ),
175   mTextureId( TextureManager::INVALID_TEXTURE_ID ),
176   mTextures(),
177   mImageVisualShaderFactory( shaderFactory ),
178   mFittingMode( fittingMode ),
179   mSamplingMode( samplingMode ),
180   mWrapModeU( WrapMode::DEFAULT ),
181   mWrapModeV( WrapMode::DEFAULT ),
182   mLoadPolicy( Toolkit::ImageVisual::LoadPolicy::ATTACHED ),
183   mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DETACHED ),
184   mAtlasRect( 0.0f, 0.0f, 0.0f, 0.0f ),
185   mAtlasRectSize( 0, 0 ),
186   mAttemptAtlasing( false ),
187   mLoading( false ),
188   mOrientationCorrection( true )
189 {
190   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
191 }
192
193 ImageVisual::ImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Image& image )
194 : Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO ),
195   mImage( image ),
196   mPixelArea( FULL_TEXTURE_RECT ),
197   mPlacementActor(),
198   mImageUrl(),
199   mMaskingData( ),
200   mDesiredSize(),
201   mTextureId( TextureManager::INVALID_TEXTURE_ID ),
202   mTextures(),
203   mImageVisualShaderFactory( shaderFactory ),
204   mFittingMode( FittingMode::DEFAULT ),
205   mSamplingMode( SamplingMode::DEFAULT ),
206   mWrapModeU( WrapMode::DEFAULT ),
207   mWrapModeV( WrapMode::DEFAULT ),
208   mLoadPolicy( Toolkit::ImageVisual::LoadPolicy::ATTACHED ),
209   mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DESTROYED ),
210   mAtlasRect( 0.0f, 0.0f, 0.0f, 0.0f ),
211   mAttemptAtlasing( false ),
212   mLoading( false ),
213   mOrientationCorrection( true )
214 {
215   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
216 }
217
218 ImageVisual::~ImageVisual()
219 {
220   if( Stage::IsInstalled() )
221   {
222     if( mMaskingData )
223     {
224       // TextureManager could have been deleted before the actor that contains this
225       // ImageVisual is destroyed (e.g. due to stage shutdown). Ensure the stage
226       // is still valid before accessing texture manager.
227       if( mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID )
228       {
229         TextureManager& textureManager = mFactoryCache.GetTextureManager();
230         textureManager.Remove( mMaskingData->mAlphaMaskId );
231       }
232     }
233
234     // ImageVisual destroyed so remove texture unless ReleasePolicy is set to never release
235     if( ( mTextureId != TextureManager::INVALID_TEXTURE_ID  ) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ) )
236     {
237       RemoveTexture();
238     }
239   }
240 }
241
242 void ImageVisual::DoSetProperties( const Property::Map& propertyMap )
243 {
244   // Url is already received in constructor
245   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
246   {
247     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
248     if( keyValue.first.type == Property::Key::INDEX )
249     {
250       DoSetProperty( keyValue.first.indexKey, keyValue.second );
251     }
252     else
253     {
254       if( keyValue.first == IMAGE_FITTING_MODE )
255       {
256         DoSetProperty( Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second );
257       }
258       else if( keyValue.first == IMAGE_SAMPLING_MODE )
259       {
260         DoSetProperty( Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second );
261       }
262       else if( keyValue.first == IMAGE_DESIRED_WIDTH )
263       {
264         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second );
265       }
266       else if( keyValue.first == IMAGE_DESIRED_HEIGHT )
267       {
268         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second );
269       }
270       else if( keyValue.first == PIXEL_AREA_UNIFORM_NAME )
271       {
272         DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second );
273       }
274       else if( keyValue.first == IMAGE_WRAP_MODE_U )
275       {
276         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second );
277       }
278       else if( keyValue.first == IMAGE_WRAP_MODE_V )
279       {
280         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second );
281       }
282       else if( keyValue.first == SYNCHRONOUS_LOADING )
283       {
284         DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
285       }
286       else if( keyValue.first == IMAGE_ATLASING )
287       {
288         DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
289       }
290       else if( keyValue.first == ALPHA_MASK_URL )
291       {
292         DoSetProperty( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second );
293       }
294       else if( keyValue.first == MASK_CONTENT_SCALE_NAME )
295       {
296         DoSetProperty( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second );
297       }
298       else if( keyValue.first == CROP_TO_MASK_NAME )
299       {
300         DoSetProperty( Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second );
301       }
302       else if ( keyValue.first == LOAD_POLICY_NAME )
303       {
304         DoSetProperty( Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second );
305       }
306       else if( keyValue.first == RELEASE_POLICY_NAME )
307       {
308         DoSetProperty( Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second );
309       }
310       else if( keyValue.first == ORIENTATION_CORRECTION_NAME )
311       {
312         DoSetProperty( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second );
313       }
314     }
315   }
316   // Load image immediately if LOAD_POLICY requires it
317   if ( mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE )
318   {
319     auto attemptAtlasing = AttemptAtlasing();
320     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
321                  TextureManager::ReloadPolicy::CACHED  );
322   }
323 }
324
325 void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
326 {
327   switch( index )
328   {
329     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
330     {
331       bool sync = false;
332       if( value.Get( sync ) )
333       {
334         if( sync )
335         {
336           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
337         }
338         else
339         {
340           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
341         }
342       }
343       else
344       {
345         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
346       }
347       break;
348     }
349
350     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
351     {
352       float desiredWidth = 0.0f;
353       if( value.Get( desiredWidth ) )
354       {
355         mDesiredSize.SetWidth( desiredWidth );
356       }
357       else
358       {
359         DALI_LOG_ERROR("ImageVisual: desiredWidth property has incorrect type\n");
360       }
361       break;
362     }
363
364     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
365     {
366       float desiredHeight = 0.0f;
367       if( value.Get( desiredHeight ) )
368       {
369         mDesiredSize.SetHeight( desiredHeight );
370       }
371       else
372       {
373         DALI_LOG_ERROR("ImageVisual: desiredHeight property has incorrect type\n");
374       }
375       break;
376     }
377
378     case Toolkit::ImageVisual::Property::FITTING_MODE:
379     {
380       int fittingMode = 0;
381       Scripting::GetEnumerationProperty( value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode );
382       mFittingMode = Dali::FittingMode::Type( fittingMode );
383       break;
384     }
385
386     case Toolkit::ImageVisual::Property::SAMPLING_MODE:
387     {
388       int samplingMode = 0;
389       Scripting::GetEnumerationProperty( value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode );
390       mSamplingMode = Dali::SamplingMode::Type( samplingMode );
391       break;
392     }
393
394     case Toolkit::ImageVisual::Property::PIXEL_AREA:
395     {
396       value.Get( mPixelArea );
397       break;
398     }
399
400     case Toolkit::ImageVisual::Property::WRAP_MODE_U:
401     {
402       int wrapMode = 0;
403       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
404       mWrapModeU = Dali::WrapMode::Type( wrapMode );
405       break;
406     }
407
408     case Toolkit::ImageVisual::Property::WRAP_MODE_V:
409     {
410       int wrapMode = 0;
411       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
412       mWrapModeV = Dali::WrapMode::Type( wrapMode );
413       break;
414     }
415
416     case Toolkit::ImageVisual::Property::ATLASING:
417     {
418       value.Get( mAttemptAtlasing );
419       break;
420     }
421
422     case Toolkit::ImageVisual::Property::ALPHA_MASK_URL:
423     {
424       std::string alphaUrl = "";
425       if( value.Get( alphaUrl ) )
426       {
427         AllocateMaskData();
428         mMaskingData->mAlphaMaskUrl = alphaUrl;
429       }
430       break;
431     }
432
433     case Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE:
434     {
435       float scale = 1.0f;
436       if( value.Get( scale ) )
437       {
438         AllocateMaskData();
439         mMaskingData->mContentScaleFactor = scale;
440       }
441       break;
442     }
443
444     case Toolkit::ImageVisual::Property::CROP_TO_MASK:
445     {
446       bool crop=false;
447       if( value.Get( crop ) )
448       {
449         AllocateMaskData();
450         mMaskingData->mCropToMask = crop;
451       }
452       break;
453     }
454
455     case Toolkit::ImageVisual::Property::RELEASE_POLICY:
456     {
457       int releasePolicy = 0;
458       Scripting::GetEnumerationProperty( value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy );
459       mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type( releasePolicy );
460       break;
461     }
462
463     case Toolkit::ImageVisual::Property::LOAD_POLICY:
464     {
465       int loadPolicy = 0;
466       Scripting::GetEnumerationProperty( value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy );
467       mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type( loadPolicy );
468       break;
469     }
470     case Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION:
471     {
472       bool orientationCorrection( mOrientationCorrection );
473       if( value.Get( orientationCorrection ) )
474       {
475         mOrientationCorrection = orientationCorrection;
476       }
477       break;
478     }
479   }
480 }
481
482 void ImageVisual::AllocateMaskData()
483 {
484   if( !mMaskingData )
485   {
486     mMaskingData.reset(new TextureManager::MaskingData());
487   }
488 }
489
490 void ImageVisual::GetNaturalSize( Vector2& naturalSize )
491 {
492   if(mImage)
493   {
494     naturalSize.x = mImage.GetWidth();
495     naturalSize.y = mImage.GetHeight();
496     return;
497   }
498   else if( mDesiredSize.GetWidth()>0 && mDesiredSize.GetHeight()>0)
499   {
500     naturalSize.x = mDesiredSize.GetWidth();
501     naturalSize.y = mDesiredSize.GetHeight();
502     return;
503   }
504   else if( mImpl->mRenderer ) // Check if we have a loaded image
505   {
506     if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
507     {
508       naturalSize.x = mAtlasRectSize.GetWidth();
509       naturalSize.y = mAtlasRectSize.GetHeight();
510       return;
511     }
512
513     auto textureSet = mImpl->mRenderer.GetTextures();
514     if( textureSet )
515     {
516       auto texture = textureSet.GetTexture(0);
517       naturalSize.x = texture.GetWidth();
518       naturalSize.y = texture.GetHeight();
519       return;
520     }
521   }
522
523   if( mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() &&
524            mMaskingData->mCropToMask )
525   {
526     ImageDimensions dimensions = Dali::GetClosestImageSize( mMaskingData->mAlphaMaskUrl.GetUrl() );
527     if( dimensions != ImageDimensions( 0, 0 ) )
528     {
529       naturalSize.x = dimensions.GetWidth();
530       naturalSize.y = dimensions.GetHeight();
531     }
532     return;
533   }
534   else if( mImageUrl.IsValid() )
535   {
536     if( mImageUrl.GetProtocolType() == VisualUrl::LOCAL )
537     {
538       ImageDimensions dimensions = Dali::GetClosestImageSize( mImageUrl.GetUrl() );
539
540       if( dimensions != ImageDimensions( 0, 0 ) )
541       {
542         naturalSize.x = dimensions.GetWidth();
543         naturalSize.y = dimensions.GetHeight();
544       }
545       else
546       {
547         Image brokenImage = mFactoryCache.GetBrokenVisualImage();
548
549         naturalSize.x = brokenImage.GetWidth();
550         naturalSize.y = brokenImage.GetWidth();
551       }
552       return;
553     }
554   }
555
556   naturalSize = Vector2::ZERO;
557 }
558
559 void ImageVisual::CreateRenderer( TextureSet& textureSet )
560 {
561   Geometry geometry;
562   Shader shader;
563
564   if( !mImpl->mCustomShader )
565   {
566     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
567
568     shader = mImageVisualShaderFactory.GetShader( mFactoryCache,
569                              mImpl->mFlags & Impl::IS_ATLASING_APPLIED,
570                              mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE );
571   }
572   else
573   {
574     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
575     if( mImpl->mCustomShader->mVertexShader.empty() && mImpl->mCustomShader->mFragmentShader.empty() )
576     {
577       // Use custom hints
578       shader = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), mImageVisualShaderFactory.GetFragmentShaderSource(), mImpl->mCustomShader->mHints );
579       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
580     }
581     else
582     {
583       shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
584                             mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource() : mImpl->mCustomShader->mFragmentShader,
585                             mImpl->mCustomShader->mHints );
586       if( mImpl->mCustomShader->mVertexShader.empty() )
587       {
588         shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
589       }
590     }
591   }
592
593   // Set pixel align off as default.
594   // ToDo: Pixel align causes issues such as rattling image animation.
595   // We should trun it off until issues are resolved
596   shader.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
597
598   mImpl->mRenderer = Renderer::New( geometry, shader );
599   if( textureSet )
600   {
601     mImpl->mRenderer.SetTextures( textureSet );
602   }
603   // else still waiting for texture load to finish.
604
605   //Register transform properties
606   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
607
608   EnablePreMultipliedAlpha( IsPreMultipliedAlphaEnabled() );
609 }
610
611 void ImageVisual::CreateNativeImageRenderer( NativeImage& nativeImage )
612 {
613   Geometry geometry;
614   Shader shader;
615
616   std::string fragmentShader;
617   const char* fragmentPreFix = nativeImage.GetCustomFragmentPreFix();
618   const char* customSamplerTypename = nativeImage.GetCustomSamplerTypename();
619
620   if( fragmentPreFix )
621   {
622     fragmentShader = fragmentPreFix;
623     fragmentShader += "\n";
624   }
625
626   if( mImpl->mCustomShader && !mImpl->mCustomShader->mFragmentShader.empty() )
627   {
628     fragmentShader += mImpl->mCustomShader->mFragmentShader;
629   }
630   else
631   {
632     fragmentShader += mImageVisualShaderFactory.GetFragmentShaderSource();
633   }
634
635   if( customSamplerTypename )
636   {
637     fragmentShader.replace( fragmentShader.find( DEFAULT_SAMPLER_TYPENAME ), strlen( DEFAULT_SAMPLER_TYPENAME ), customSamplerTypename );
638   }
639
640   if( !mImpl->mCustomShader )
641   {
642     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
643
644     shader  = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), fragmentShader );
645     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
646   }
647   else
648   {
649     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
650     shader  = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
651                            fragmentShader,
652                            mImpl->mCustomShader->mHints );
653     if( mImpl->mCustomShader->mVertexShader.empty() )
654     {
655       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
656     }
657   }
658
659   mImpl->mRenderer = Renderer::New( geometry, shader );
660
661   //Register transform properties
662   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
663 }
664
665 bool ImageVisual::IsSynchronousResourceLoading() const
666 {
667   return mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
668 }
669
670 void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection,
671                                TextureManager::ReloadPolicy forceReload )
672 {
673   TextureManager& textureManager = mFactoryCache.GetTextureManager();
674
675   ImageAtlasManagerPtr atlasManager = nullptr;
676   AtlasUploadObserver* atlasUploadObserver = nullptr;
677   auto textureObserver = this;
678
679   if( atlasing )
680   {
681     atlasManager = mFactoryCache.GetAtlasManager();
682     atlasUploadObserver = this;
683   }
684
685   auto preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader
686     ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
687     : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
688
689   textures = textureManager.LoadTexture( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode,
690                                          mMaskingData, IsSynchronousResourceLoading(), mTextureId,
691                                          atlasRect, mAtlasRectSize, atlasing, mLoading, mWrapModeU,
692                                          mWrapModeV, textureObserver, atlasUploadObserver, atlasManager,
693                                          mOrientationCorrection, forceReload, preMultiplyOnLoad);
694
695   if( textures )
696   {
697     EnablePreMultipliedAlpha( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
698   }
699
700   if( atlasing ) // Flag needs to be set before creating renderer
701   {
702     mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
703   }
704   else
705   {
706     mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
707   }
708 }
709
710 bool ImageVisual::AttemptAtlasing()
711 {
712   return ( ! mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing );
713 }
714
715 void ImageVisual::InitializeRenderer()
716 {
717   auto attemptAtlasing = AttemptAtlasing();
718   // texture set has to be created first as we need to know if atlasing succeeded or not
719   // when selecting the shader
720
721   if( mTextureId == TextureManager::INVALID_TEXTURE_ID && ! mTextures ) // Only load the texture once
722   {
723     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
724                  TextureManager::ReloadPolicy::CACHED );
725   }
726
727   CreateRenderer( mTextures );
728   mTextures.Reset(); // Visual should not keep a handle to the texture after this point.
729
730   if( attemptAtlasing ) // the texture is packed inside atlas
731   {
732     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
733
734     bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
735
736     if( !defaultWrapMode ) // custom wrap mode
737     {
738       Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE);
739       wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) );
740       mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode );
741     }
742   }
743 }
744
745 void ImageVisual::InitializeRenderer( const Image& image )
746 {
747   TextureSet textures = TextureSet::New();
748
749   NativeImage nativeImage = NativeImage::DownCast( image );
750   if( nativeImage )
751   {
752     CreateNativeImageRenderer( nativeImage );
753     DALI_ASSERT_DEBUG( textures );
754     mImpl->mRenderer.SetTextures( textures );
755   }
756   else
757   {
758     // reuse existing code for regular images
759     CreateRenderer( textures ); // Textures will be retreived from Image
760   }
761   ApplyImageToSampler( image );
762 }
763
764 void ImageVisual::DoSetOnStage( Actor& actor )
765 {
766   if( mImageUrl.IsValid() )
767   {
768     InitializeRenderer();
769   }
770   else if( mImage )
771   {
772     InitializeRenderer( mImage );
773   }
774
775   if( !mImpl->mRenderer )
776   {
777     return;
778   }
779
780   mPlacementActor = actor;
781   // Search the Actor tree to find if Layer UI behaviour set.
782   Layer layer = actor.GetLayer();
783   if( layer && layer.GetBehavior() == Layer::LAYER_3D )
784   {
785      // Layer 3D set, do not align pixels
786      mImpl->mRenderer.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
787   }
788
789   if( mPixelArea != FULL_TEXTURE_RECT )
790   {
791     mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea );
792   }
793
794   if( mLoading == false )
795   {
796     actor.AddRenderer( mImpl->mRenderer );
797     mPlacementActor.Reset();
798
799     // Image loaded and ready to display
800     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
801   }
802 }
803
804 void ImageVisual::DoSetOffStage( Actor& actor )
805 {
806   // Visual::Base::SetOffStage only calls DoSetOffStage if mRenderer exists (is on onstage)
807
808   // Image release is dependent on the ReleasePolicy, renderer is destroyed.
809   actor.RemoveRenderer( mImpl->mRenderer);
810   if( mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED )
811   {
812     RemoveTexture(); // If INVALID_TEXTURE_ID then removal will be attempted on atlas
813     mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
814   }
815
816   if( mImageUrl.IsValid() )
817   {
818     // Legacy support for deprecated Dali::Image
819     mImage.Reset();
820   }
821   mLoading = false;
822   mImpl->mRenderer.Reset();
823   mPlacementActor.Reset();
824 }
825
826 void ImageVisual::DoCreatePropertyMap( Property::Map& map ) const
827 {
828   map.Clear();
829   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
830
831   bool sync = IsSynchronousResourceLoading();
832   map.Insert( SYNCHRONOUS_LOADING, sync );
833   if( mImageUrl.IsValid() )
834   {
835     map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
836     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
837     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
838   }
839   else if( mImage )
840   {
841     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
842     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
843
844     ResourceImage resourceImage = ResourceImage::DownCast(mImage);
845     if( resourceImage )
846     {
847       map.Insert( Toolkit::ImageVisual::Property::URL, resourceImage.GetUrl() );
848     }
849   }
850
851   map.Insert( Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode );
852   map.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode );
853
854   map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea );
855   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU );
856   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV );
857
858   map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
859
860   if( mMaskingData != NULL )
861   {
862     map.Insert( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl() );
863     map.Insert( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor );
864     map.Insert( Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask );
865   }
866
867   map.Insert( Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy );
868   map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
869   map.Insert( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection );
870 }
871
872 void ImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
873 {
874   map.Clear();
875   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
876   if( mImageUrl.IsValid() )
877   {
878     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
879     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
880   }
881   else if( mImage )
882   {
883     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
884     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
885   }
886 }
887
888 void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali::Property::Value& attributes )
889 {
890   // Check if action is valid for this visual type and perform action if possible
891
892   switch ( actionName )
893   {
894     case DevelImageVisual::Action::RELOAD:
895     {
896       auto attemptAtlasing = AttemptAtlasing();
897       LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
898                    TextureManager::ReloadPolicy::FORCED );
899       break;
900     }
901   }
902 }
903
904 void ImageVisual::OnSetTransform()
905 {
906   if( mImpl->mRenderer )
907   {
908     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
909   }
910 }
911
912 bool ImageVisual::IsResourceReady() const
913 {
914   return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
915            mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
916 }
917
918 void ImageVisual::ApplyImageToSampler( const Image& image )
919 {
920   if( image )
921   {
922     TextureSet textureSet = mImpl->mRenderer.GetTextures();
923     DALI_ASSERT_DEBUG( textureSet ); // texture set should always exist by this time
924
925     TextureSetImage( textureSet, 0u, image );
926     Sampler sampler = Sampler::New();
927     sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
928     textureSet.SetSampler( 0u, sampler );
929   }
930 }
931
932 // From existing atlas manager
933 void ImageVisual::UploadCompleted()
934 {
935   // Texture has been uploaded. If weak handle is holding a placement actor,
936   // it is the time to add the renderer to actor.
937   Actor actor = mPlacementActor.GetHandle();
938   if( actor )
939   {
940     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
941     actor.AddRenderer( mImpl->mRenderer );
942     // reset the weak handle so that the renderer only get added to actor once
943     mPlacementActor.Reset();
944   }
945   // Image loaded
946   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
947   mLoading = false;
948 }
949
950 // From Texture Manager
951 void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas,
952                                   const Vector4& atlasRectangle, bool preMultiplied )
953 {
954   Toolkit::Visual::ResourceStatus resourceStatus;
955   if( mImpl->mRenderer )
956   {
957     if( usingAtlas )
958     {
959       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
960     }
961
962     EnablePreMultipliedAlpha( preMultiplied );
963
964     Actor actor = mPlacementActor.GetHandle();
965     if( actor )
966     {
967       actor.AddRenderer( mImpl->mRenderer );
968       // reset the weak handle so that the renderer only get added to actor once
969       mPlacementActor.Reset();
970     }
971
972     if( loadingSuccess )
973     {
974       Sampler sampler = Sampler::New();
975       sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
976       textureSet.SetSampler( 0u, sampler );
977       mImpl->mRenderer.SetTextures(textureSet);
978     }
979     else
980     {
981       Image brokenImage = mFactoryCache.GetBrokenVisualImage();
982
983       textureSet = TextureSet::New();
984       mImpl->mRenderer.SetTextures( textureSet );
985
986       ApplyImageToSampler( brokenImage );
987     }
988   }
989
990   // Storing TextureSet needed when renderer staged.
991   if( ! mImpl->mRenderer )
992   {
993     mTextures = textureSet;
994   }
995
996   // Image loaded, set status regardless of staged status.
997   if( loadingSuccess )
998   {
999     resourceStatus = Toolkit::Visual::ResourceStatus::READY;
1000   }
1001   else
1002   {
1003     resourceStatus = Toolkit::Visual::ResourceStatus::FAILED;
1004   }
1005   // Signal to observers ( control ) that resources are ready. Must be all resources.
1006   ResourceReady( resourceStatus );
1007   mLoading = false;
1008 }
1009
1010 void ImageVisual::RemoveTexture()
1011 {
1012   if( mTextureId != TextureManager::INVALID_TEXTURE_ID )
1013   {
1014     mFactoryCache.GetTextureManager().Remove( mTextureId );
1015     mTextureId = TextureManager::INVALID_TEXTURE_ID;
1016   }
1017   else
1018   {
1019     Vector4 atlasRect( 0.f, 0.f, 1.f, 1.f );
1020     Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
1021     if( index != Property::INVALID_INDEX )
1022     {
1023       Property::Value atlasRectValue = mImpl->mRenderer.GetProperty( index );
1024       atlasRectValue.Get( atlasRect );
1025     }
1026
1027     TextureSet textureSet = mImpl->mRenderer.GetTextures();
1028     mImpl->mRenderer.Reset();
1029
1030     if( index != Property::INVALID_INDEX )
1031     {
1032       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
1033     }
1034   }
1035 }
1036
1037 } // namespace Internal
1038
1039 } // namespace Toolkit
1040
1041 } // namespace Dali