[4.0] Add ImageVisualShaderFactory
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / image / image-visual.cpp
1 /*
2  * Copyright (c) 2018 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 ),
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   mAttemptAtlasing( false ),
186   mLoading( false ),
187   mOrientationCorrection( true )
188 {
189 }
190
191 ImageVisual::ImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Image& image )
192 : Visual::Base( factoryCache ),
193   mImage( image ),
194   mPixelArea( FULL_TEXTURE_RECT ),
195   mPlacementActor(),
196   mImageUrl(),
197   mMaskingData( ),
198   mDesiredSize(),
199   mTextureId( TextureManager::INVALID_TEXTURE_ID ),
200   mTextures(),
201   mImageVisualShaderFactory( shaderFactory ),
202   mFittingMode( FittingMode::DEFAULT ),
203   mSamplingMode( SamplingMode::DEFAULT ),
204   mWrapModeU( WrapMode::DEFAULT ),
205   mWrapModeV( WrapMode::DEFAULT ),
206   mLoadPolicy( Toolkit::ImageVisual::LoadPolicy::ATTACHED ),
207   mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DESTROYED ),
208   mAtlasRect( 0.0f, 0.0f, 0.0f, 0.0f ),
209   mAttemptAtlasing( false ),
210   mLoading( false ),
211   mOrientationCorrection( true )
212 {
213 }
214
215 ImageVisual::~ImageVisual()
216 {
217   if( Stage::IsInstalled() )
218   {
219     if( mMaskingData )
220     {
221       // TextureManager could have been deleted before the actor that contains this
222       // ImageVisual is destroyed (e.g. due to stage shutdown). Ensure the stage
223       // is still valid before accessing texture manager.
224       if( mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID )
225       {
226         TextureManager& textureManager = mFactoryCache.GetTextureManager();
227         textureManager.Remove( mMaskingData->mAlphaMaskId );
228       }
229     }
230
231     // ImageVisual destroyed so remove texture unless ReleasePolicy is set to never release
232     if( ( mTextureId != TextureManager::INVALID_TEXTURE_ID  ) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ) )
233     {
234       RemoveTexture();
235     }
236   }
237 }
238
239 void ImageVisual::DoSetProperties( const Property::Map& propertyMap )
240 {
241   // Url is already received in constructor
242   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
243   {
244     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
245     if( keyValue.first.type == Property::Key::INDEX )
246     {
247       DoSetProperty( keyValue.first.indexKey, keyValue.second );
248     }
249     else
250     {
251       if( keyValue.first == IMAGE_FITTING_MODE )
252       {
253         DoSetProperty( Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second );
254       }
255       else if( keyValue.first == IMAGE_SAMPLING_MODE )
256       {
257         DoSetProperty( Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second );
258       }
259       else if( keyValue.first == IMAGE_DESIRED_WIDTH )
260       {
261         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second );
262       }
263       else if( keyValue.first == IMAGE_DESIRED_HEIGHT )
264       {
265         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second );
266       }
267       else if( keyValue.first == PIXEL_AREA_UNIFORM_NAME )
268       {
269         DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second );
270       }
271       else if( keyValue.first == IMAGE_WRAP_MODE_U )
272       {
273         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second );
274       }
275       else if( keyValue.first == IMAGE_WRAP_MODE_V )
276       {
277         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second );
278       }
279       else if( keyValue.first == SYNCHRONOUS_LOADING )
280       {
281         DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
282       }
283       else if( keyValue.first == IMAGE_ATLASING )
284       {
285         DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
286       }
287       else if( keyValue.first == ALPHA_MASK_URL )
288       {
289         DoSetProperty( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second );
290       }
291       else if( keyValue.first == MASK_CONTENT_SCALE_NAME )
292       {
293         DoSetProperty( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second );
294       }
295       else if( keyValue.first == CROP_TO_MASK_NAME )
296       {
297         DoSetProperty( Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second );
298       }
299       else if ( keyValue.first == LOAD_POLICY_NAME )
300       {
301         DoSetProperty( Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second );
302       }
303       else if( keyValue.first == RELEASE_POLICY_NAME )
304       {
305         DoSetProperty( Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second );
306       }
307       else if( keyValue.first == ORIENTATION_CORRECTION_NAME )
308       {
309         DoSetProperty( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second );
310       }
311     }
312   }
313   // Load image immediately if LOAD_POLICY requires it
314   if ( mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE )
315   {
316     auto attemptAtlasing = AttemptAtlasing();
317     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
318                  TextureManager::ReloadPolicy::CACHED  );
319   }
320 }
321
322 void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
323 {
324   switch( index )
325   {
326     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
327     {
328       bool sync = false;
329       if( value.Get( sync ) )
330       {
331         if( sync )
332         {
333           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
334         }
335         else
336         {
337           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
338         }
339       }
340       else
341       {
342         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
343       }
344       break;
345     }
346
347     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
348     {
349       float desiredWidth = 0.0f;
350       if( value.Get( desiredWidth ) )
351       {
352         mDesiredSize.SetWidth( desiredWidth );
353       }
354       else
355       {
356         DALI_LOG_ERROR("ImageVisual: desiredWidth property has incorrect type\n");
357       }
358       break;
359     }
360
361     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
362     {
363       float desiredHeight = 0.0f;
364       if( value.Get( desiredHeight ) )
365       {
366         mDesiredSize.SetHeight( desiredHeight );
367       }
368       else
369       {
370         DALI_LOG_ERROR("ImageVisual: desiredHeight property has incorrect type\n");
371       }
372       break;
373     }
374
375     case Toolkit::ImageVisual::Property::FITTING_MODE:
376     {
377       int fittingMode = 0;
378       Scripting::GetEnumerationProperty( value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode );
379       mFittingMode = Dali::FittingMode::Type( fittingMode );
380       break;
381     }
382
383     case Toolkit::ImageVisual::Property::SAMPLING_MODE:
384     {
385       int samplingMode = 0;
386       Scripting::GetEnumerationProperty( value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode );
387       mSamplingMode = Dali::SamplingMode::Type( samplingMode );
388       break;
389     }
390
391     case Toolkit::ImageVisual::Property::PIXEL_AREA:
392     {
393       value.Get( mPixelArea );
394       break;
395     }
396
397     case Toolkit::ImageVisual::Property::WRAP_MODE_U:
398     {
399       int wrapMode = 0;
400       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
401       mWrapModeU = Dali::WrapMode::Type( wrapMode );
402       break;
403     }
404
405     case Toolkit::ImageVisual::Property::WRAP_MODE_V:
406     {
407       int wrapMode = 0;
408       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
409       mWrapModeV = Dali::WrapMode::Type( wrapMode );
410       break;
411     }
412
413     case Toolkit::ImageVisual::Property::ATLASING:
414     {
415       value.Get( mAttemptAtlasing );
416       break;
417     }
418
419     case Toolkit::ImageVisual::Property::ALPHA_MASK_URL:
420     {
421       std::string alphaUrl = "";
422       if( value.Get( alphaUrl ) )
423       {
424         AllocateMaskData();
425         // Immediately trigger the alpha mask loading (it may just get a cached value)
426         mMaskingData->mAlphaMaskUrl = alphaUrl;
427         TextureManager& textureManager = mFactoryCache.GetTextureManager();
428         mMaskingData->mAlphaMaskId = textureManager.RequestMaskLoad( 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     auto textureSet = mImpl->mRenderer.GetTextures();
507
508     if( textureSet )
509     {
510       auto texture = textureSet.GetTexture(0);
511       naturalSize.x = texture.GetWidth();
512       naturalSize.y = texture.GetHeight();
513       return;
514     }
515   }
516
517   if( mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() &&
518            mMaskingData->mCropToMask )
519   {
520     ImageDimensions dimensions = Dali::GetClosestImageSize( mMaskingData->mAlphaMaskUrl.GetUrl() );
521     if( dimensions != ImageDimensions( 0, 0 ) )
522     {
523       naturalSize.x = dimensions.GetWidth();
524       naturalSize.y = dimensions.GetHeight();
525     }
526     return;
527   }
528   else if( mImageUrl.IsValid() )
529   {
530     if( mImageUrl.GetProtocolType() == VisualUrl::LOCAL )
531     {
532       ImageDimensions dimensions = Dali::GetClosestImageSize( mImageUrl.GetUrl() );
533
534       if( dimensions != ImageDimensions( 0, 0 ) )
535       {
536         naturalSize.x = dimensions.GetWidth();
537         naturalSize.y = dimensions.GetHeight();
538       }
539       else
540       {
541         Image brokenImage = VisualFactoryCache::GetBrokenVisualImage();
542
543         naturalSize.x = brokenImage.GetWidth();
544         naturalSize.y = brokenImage.GetWidth();
545       }
546       return;
547     }
548   }
549
550   naturalSize = Vector2::ZERO;
551 }
552
553 void ImageVisual::CreateRenderer( TextureSet& textureSet )
554 {
555   Geometry geometry;
556   Shader shader;
557
558   if( !mImpl->mCustomShader )
559   {
560     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
561
562     shader = mImageVisualShaderFactory.GetShader( mFactoryCache,
563                              mImpl->mFlags & Impl::IS_ATLASING_APPLIED,
564                              mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE );
565   }
566   else
567   {
568     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
569     if( mImpl->mCustomShader->mVertexShader.empty() && mImpl->mCustomShader->mFragmentShader.empty() )
570     {
571       // Use custom hints
572       shader = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), mImageVisualShaderFactory.GetFragmentShaderSource(), mImpl->mCustomShader->mHints );
573       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
574     }
575     else
576     {
577       shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
578                             mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource() : mImpl->mCustomShader->mFragmentShader,
579                             mImpl->mCustomShader->mHints );
580       if( mImpl->mCustomShader->mVertexShader.empty() )
581       {
582         shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
583       }
584     }
585   }
586
587   // Set pixel align off as default.
588   // ToDo: Pixel align causes issues such as rattling image animation.
589   // We should trun it off until issues are resolved
590   shader.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
591
592   mImpl->mRenderer = Renderer::New( geometry, shader );
593   if( textureSet )
594   {
595     mImpl->mRenderer.SetTextures( textureSet );
596   }
597   // else still waiting for texture load to finish.
598
599   //Register transform properties
600   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
601
602   EnablePreMultipliedAlpha( IsPreMultipliedAlphaEnabled() );
603 }
604
605 void ImageVisual::CreateNativeImageRenderer( NativeImage& nativeImage )
606 {
607   Geometry geometry;
608   Shader shader;
609
610   std::string fragmentShader;
611   const char* fragmentPreFix = nativeImage.GetCustomFragmentPreFix();
612   const char* customSamplerTypename = nativeImage.GetCustomSamplerTypename();
613
614   if( fragmentPreFix )
615   {
616     fragmentShader = fragmentPreFix;
617     fragmentShader += "\n";
618   }
619
620   if( mImpl->mCustomShader && !mImpl->mCustomShader->mFragmentShader.empty() )
621   {
622     fragmentShader += mImpl->mCustomShader->mFragmentShader;
623   }
624   else
625   {
626     fragmentShader += mImageVisualShaderFactory.GetFragmentShaderSource();
627   }
628
629   if( customSamplerTypename )
630   {
631     fragmentShader.replace( fragmentShader.find( DEFAULT_SAMPLER_TYPENAME ), strlen( DEFAULT_SAMPLER_TYPENAME ), customSamplerTypename );
632   }
633
634   if( !mImpl->mCustomShader )
635   {
636     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
637
638     shader  = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), fragmentShader );
639     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
640   }
641   else
642   {
643     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
644     shader  = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
645                            fragmentShader,
646                            mImpl->mCustomShader->mHints );
647     if( mImpl->mCustomShader->mVertexShader.empty() )
648     {
649       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
650     }
651   }
652
653   mImpl->mRenderer = Renderer::New( geometry, shader );
654
655   //Register transform properties
656   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
657 }
658
659 bool ImageVisual::IsSynchronousResourceLoading() const
660 {
661   return mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
662 }
663
664 void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection,
665                                TextureManager::ReloadPolicy forceReload )
666 {
667   TextureManager& textureManager = mFactoryCache.GetTextureManager();
668
669   ImageAtlasManagerPtr atlasManager = nullptr;
670   AtlasUploadObserver* atlasUploadObserver = nullptr;
671   auto textureObserver = this;
672
673   if( atlasing )
674   {
675     atlasManager = mFactoryCache.GetAtlasManager();
676     atlasUploadObserver = this;
677   }
678
679   auto preMultiplyOnLoad = mFactoryCache.GetPreMultiplyOnLoad() && !mImpl->mCustomShader
680     ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
681     : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
682
683   textures = textureManager.LoadTexture( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode,
684                                          mMaskingData, IsSynchronousResourceLoading(), mTextureId,
685                                          atlasRect, atlasing, mLoading, mWrapModeU,
686                                          mWrapModeV, textureObserver, atlasUploadObserver, atlasManager,
687                                          mOrientationCorrection, forceReload, preMultiplyOnLoad);
688
689   if( textures )
690   {
691     EnablePreMultipliedAlpha( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
692   }
693
694   if( atlasing ) // Flag needs to be set before creating renderer
695   {
696     mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
697   }
698   else
699   {
700     mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
701   }
702 }
703
704 bool ImageVisual::AttemptAtlasing()
705 {
706   return ( ! mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing );
707 }
708
709 void ImageVisual::InitializeRenderer()
710 {
711   auto attemptAtlasing = AttemptAtlasing();
712   // texture set has to be created first as we need to know if atlasing succeeded or not
713   // when selecting the shader
714
715   if( mTextureId == TextureManager::INVALID_TEXTURE_ID && ! mTextures ) // Only load the texture once
716   {
717     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
718                  TextureManager::ReloadPolicy::CACHED );
719   }
720
721   CreateRenderer( mTextures );
722   mTextures.Reset(); // Visual should not keep a handle to the texture after this point.
723
724   if( attemptAtlasing ) // the texture is packed inside atlas
725   {
726     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
727
728     bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
729
730     if( !defaultWrapMode ) // custom wrap mode
731     {
732       Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE);
733       wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) );
734       mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode );
735     }
736   }
737 }
738
739 void ImageVisual::InitializeRenderer( const Image& image )
740 {
741   TextureSet textures = TextureSet::New();
742
743   NativeImage nativeImage = NativeImage::DownCast( image );
744   if( nativeImage )
745   {
746     CreateNativeImageRenderer( nativeImage );
747     DALI_ASSERT_DEBUG( textures );
748     mImpl->mRenderer.SetTextures( textures );
749   }
750   else
751   {
752     // reuse existing code for regular images
753     CreateRenderer( textures ); // Textures will be retreived from Image
754   }
755   ApplyImageToSampler( image );
756 }
757
758 void ImageVisual::DoSetOnStage( Actor& actor )
759 {
760   if( mImageUrl.IsValid() )
761   {
762     InitializeRenderer();
763   }
764   else if( mImage )
765   {
766     InitializeRenderer( mImage );
767   }
768
769   if( !mImpl->mRenderer )
770   {
771     return;
772   }
773
774   mPlacementActor = actor;
775   // Search the Actor tree to find if Layer UI behaviour set.
776   Layer layer = actor.GetLayer();
777   if( layer && layer.GetBehavior() == Layer::LAYER_3D )
778   {
779      // Layer 3D set, do not align pixels
780      mImpl->mRenderer.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
781   }
782
783   if( mPixelArea != FULL_TEXTURE_RECT )
784   {
785     mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea );
786   }
787
788   if( mLoading == false )
789   {
790     actor.AddRenderer( mImpl->mRenderer );
791     mPlacementActor.Reset();
792
793     // Image loaded and ready to display
794     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
795   }
796 }
797
798 void ImageVisual::DoSetOffStage( Actor& actor )
799 {
800   // Visual::Base::SetOffStage only calls DoSetOffStage if mRenderer exists (is on onstage)
801
802   // Image release is dependent on the ReleasePolicy, renderer is destroyed.
803   actor.RemoveRenderer( mImpl->mRenderer);
804   if( mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED )
805   {
806     RemoveTexture(); // If INVALID_TEXTURE_ID then removal will be attempted on atlas
807   }
808
809   if( mImageUrl.IsValid() )
810   {
811     // Legacy support for deprecated Dali::Image
812     mImage.Reset();
813   }
814   mLoading = false;
815   mImpl->mRenderer.Reset();
816   mPlacementActor.Reset();
817 }
818
819 void ImageVisual::DoCreatePropertyMap( Property::Map& map ) const
820 {
821   map.Clear();
822   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
823
824   bool sync = IsSynchronousResourceLoading();
825   map.Insert( SYNCHRONOUS_LOADING, sync );
826   if( mImageUrl.IsValid() )
827   {
828     map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
829     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
830     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
831   }
832   else if( mImage )
833   {
834     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
835     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
836
837     ResourceImage resourceImage = ResourceImage::DownCast(mImage);
838     if( resourceImage )
839     {
840       map.Insert( Toolkit::ImageVisual::Property::URL, resourceImage.GetUrl() );
841     }
842   }
843
844   map.Insert( Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode );
845   map.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode );
846
847   map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea );
848   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU );
849   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV );
850
851   map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
852
853   if( mMaskingData != NULL )
854   {
855     map.Insert( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl() );
856     map.Insert( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor );
857     map.Insert( Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask );
858   }
859
860   map.Insert( Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy );
861   map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
862   map.Insert( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection );
863 }
864
865 void ImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
866 {
867   map.Clear();
868   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
869   if( mImageUrl.IsValid() )
870   {
871     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
872     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
873   }
874   else if( mImage )
875   {
876     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
877     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
878   }
879 }
880
881 void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali::Property::Value& attributes )
882 {
883   // Check if action is valid for this visual type and perform action if possible
884
885   switch ( actionName )
886   {
887     case DevelImageVisual::Action::RELOAD:
888     {
889       auto attemptAtlasing = AttemptAtlasing();
890       LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
891                    TextureManager::ReloadPolicy::FORCED );
892       break;
893     }
894   }
895 }
896
897 void ImageVisual::OnSetTransform()
898 {
899   if( mImpl->mRenderer )
900   {
901     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
902   }
903 }
904
905 bool ImageVisual::IsResourceReady() const
906 {
907   return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
908            mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
909 }
910
911 void ImageVisual::ApplyImageToSampler( const Image& image )
912 {
913   if( image )
914   {
915     TextureSet textureSet = mImpl->mRenderer.GetTextures();
916     DALI_ASSERT_DEBUG( textureSet ); // texture set should always exist by this time
917
918     TextureSetImage( textureSet, 0u, image );
919     Sampler sampler = Sampler::New();
920     sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
921     textureSet.SetSampler( 0u, sampler );
922   }
923 }
924
925 // From existing atlas manager
926 void ImageVisual::UploadCompleted()
927 {
928   // Texture has been uploaded. If weak handle is holding a placement actor,
929   // it is the time to add the renderer to actor.
930   Actor actor = mPlacementActor.GetHandle();
931   if( actor )
932   {
933     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
934     actor.AddRenderer( mImpl->mRenderer );
935     // reset the weak handle so that the renderer only get added to actor once
936     mPlacementActor.Reset();
937   }
938   // Image loaded
939   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
940   mLoading = false;
941 }
942
943 // From Texture Manager
944 void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas,
945                                   const Vector4& atlasRectangle, bool preMultiplied )
946 {
947   Toolkit::Visual::ResourceStatus resourceStatus;
948   Actor actor = mPlacementActor.GetHandle();
949   if( actor )
950   {
951     if( mImpl->mRenderer )
952     {
953       if( usingAtlas )
954       {
955         mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
956       }
957
958       EnablePreMultipliedAlpha( preMultiplied );
959
960       actor.AddRenderer( mImpl->mRenderer );
961       // reset the weak handle so that the renderer only get added to actor once
962       mPlacementActor.Reset();
963       if( loadingSuccess )
964       {
965         Sampler sampler = Sampler::New();
966         sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
967         textureSet.SetSampler( 0u, sampler );
968         mImpl->mRenderer.SetTextures(textureSet);
969       }
970       else
971       {
972         Image brokenImage = VisualFactoryCache::GetBrokenVisualImage();
973
974         textureSet = TextureSet::New();
975         mImpl->mRenderer.SetTextures( textureSet );
976
977         ApplyImageToSampler( brokenImage );
978       }
979     }
980   }
981   // Storing TextureSet needed when renderer staged.
982   if( ! mImpl->mRenderer )
983   {
984     mTextures = textureSet;
985   }
986
987   // Image loaded, set status regardless of staged status.
988   if( loadingSuccess )
989   {
990     resourceStatus = Toolkit::Visual::ResourceStatus::READY;
991   }
992   else
993   {
994     resourceStatus = Toolkit::Visual::ResourceStatus::FAILED;
995   }
996   // Signal to observers ( control ) that resources are ready. Must be all resources.
997   ResourceReady( resourceStatus );
998   mLoading = false;
999 }
1000
1001 void ImageVisual::RemoveTexture()
1002 {
1003   if( mTextureId != TextureManager::INVALID_TEXTURE_ID )
1004   {
1005     mFactoryCache.GetTextureManager().Remove( mTextureId );
1006     mTextureId = TextureManager::INVALID_TEXTURE_ID;
1007   }
1008   else
1009   {
1010     Vector4 atlasRect( 0.f, 0.f, 1.f, 1.f );
1011     Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
1012     if( index != Property::INVALID_INDEX )
1013     {
1014       Property::Value atlasRectValue = mImpl->mRenderer.GetProperty( index );
1015       atlasRectValue.Get( atlasRect );
1016     }
1017
1018     TextureSet textureSet = mImpl->mRenderer.GetTextures();
1019     mImpl->mRenderer.Reset();
1020
1021     if( index != Property::INVALID_INDEX )
1022     {
1023       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
1024     }
1025   }
1026 }
1027
1028 } // namespace Internal
1029
1030 } // namespace Toolkit
1031
1032 } // namespace Dali