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