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