Image class Usage Removal
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / npatch / npatch-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 "npatch-visual.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/object/handle-devel.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/integration-api/debug.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
29 #include <dali-toolkit/public-api/visuals/visual-properties.h>
30 #include <dali-toolkit/internal/visuals/npatch-loader.h>
31 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
33 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
34 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
36
37 namespace Dali
38 {
39
40 namespace Toolkit
41 {
42
43 namespace Internal
44 {
45
46 namespace
47 {
48 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
49   attribute mediump vec2 aPosition;\n
50   varying mediump vec2 vTexCoord;\n
51   varying mediump vec2 vMaskTexCoord;\n
52   uniform highp   mat4 uMvpMatrix;\n
53   uniform mediump vec3 uSize;\n
54   uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
55   uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
56   \n
57
58   // Visual size and offset
59   uniform mediump vec2 offset;\n
60   uniform mediump vec2 size;\n
61   uniform mediump vec4 offsetSizeMode;\n
62   uniform mediump vec2 origin;\n
63   uniform mediump vec2 anchorPoint;\n
64   uniform mediump vec2 extraSize;\n
65
66   void main()\n
67   {\n
68     mediump vec2 fixedFactor  = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
69     mediump vec2 stretch      = vec2( uNinePatchFactorsX[ int( ( aPosition.x       ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y       ) * 0.5 ) ].y );\n
70     \n
71     mediump vec2 fixedTotal   = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
72     mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
73     \n
74     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
75     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
76     \n
77     mediump vec4 gridPosition = vec4( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal, 0.0, 1.0 );\n
78     mediump vec4 vertexPosition = gridPosition;\n
79     vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
80     vertexPosition.xy += anchorPoint*visualSize + (visualOffset + origin)*uSize.xy;\n
81     vertexPosition = uMvpMatrix * vertexPosition;\n
82     \n
83     vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
84     vMaskTexCoord = gridPosition.xy / visualSize;\n
85     \n
86     gl_Position = vertexPosition;\n
87   }\n
88 );
89
90 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
91     attribute mediump vec2 aPosition;\n
92     varying mediump vec2 vTexCoord;\n
93     varying mediump vec2 vMaskTexCoord;\n
94     uniform highp   mat4 uMvpMatrix;\n
95     uniform mediump vec3 uSize;\n
96     uniform mediump vec2 uFixed[ 3 ];\n
97     uniform mediump vec2 uStretchTotal;\n
98     \n
99     //Visual size and offset
100     uniform mediump vec2 offset;\n
101     uniform mediump vec2 size;\n
102     uniform mediump vec4 offsetSizeMode;\n
103     uniform mediump vec2 origin;\n
104     uniform mediump vec2 anchorPoint;\n
105     uniform mediump vec2 extraSize;\n
106     \n
107     void main()\n
108     {\n
109       vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
110       vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
111       \n
112       mediump vec2 size         = visualSize.xy;\n
113       \n
114       mediump vec2 fixedFactor  = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y  + 1.0 ) * 0.5 ) ].y );\n
115       mediump vec2 stretch      = floor( aPosition * 0.5 );\n
116       mediump vec2 fixedTotal   = uFixed[ 2 ];\n
117       \n
118       mediump vec4 gridPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
119       mediump vec4 vertexPosition = gridPosition;\n
120       vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
121       vertexPosition.xy += anchorPoint*size + (visualOffset + origin)*uSize.xy;\n
122       \n
123       vertexPosition = uMvpMatrix * vertexPosition;\n
124       \n
125       vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
126       \n
127       vMaskTexCoord = gridPosition.xy / size;\n
128       gl_Position = vertexPosition;\n
129     }\n
130 );
131
132 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
133   varying mediump vec2 vTexCoord;\n
134   uniform sampler2D sTexture;\n
135   uniform lowp vec4 uColor;\n
136   uniform lowp vec3 mixColor;\n
137   uniform lowp float preMultipliedAlpha;\n
138   \n
139   void main()\n
140   {\n
141     gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * vec4( mixColor, 1.0 );\n
142   }\n
143 );
144
145 const char* FRAGMENT_MASK_SHADER = DALI_COMPOSE_SHADER(
146   varying mediump vec2 vTexCoord;\n
147   varying mediump vec2 vMaskTexCoord;\n
148   uniform sampler2D sTexture;\n
149   uniform sampler2D sMask;\n
150   uniform lowp vec4 uColor;\n
151   uniform lowp vec3 mixColor;\n
152   uniform lowp float preMultipliedAlpha;\n
153   uniform mediump float auxiliaryImageAlpha;\n
154   \n
155   void main()\n
156   {\n
157       // Where mask image is transparent, all of background image must show through.
158       // where mask image is opaque, only mask should be shown
159       // where mask is translucent, less of background should be shown.
160       // auxiliaryImageAlpha controls how much of mask is visible
161
162       mediump vec4 color = texture2D( sTexture, vTexCoord );\n
163       mediump vec4 mask  = texture2D( sMask, vMaskTexCoord );\n
164
165       mediump vec3 mixedColor = color.rgb * mix( 1.0-mask.a, 1.0, 1.0-auxiliaryImageAlpha)
166                                 + mask.rgb*mask.a * auxiliaryImageAlpha;\n
167       gl_FragColor = vec4(mixedColor,1.0) * uColor * vec4( mixColor, 1.0 );\n
168   }\n
169 );
170
171 /**
172  * @brief Creates the geometry formed from the vertices and indices
173  *
174  * @param[in]  vertices             The vertices to generate the geometry from
175  * @param[in]  indices              The indices to generate the geometry from
176  * @return The geometry formed from the vertices and indices
177  */
178 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
179 {
180   Property::Map vertexFormat;
181   vertexFormat[ "aPosition" ] = Property::VECTOR2;
182   PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
183   if( vertices.Size() > 0 )
184   {
185     vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
186   }
187
188   // Create the geometry object
189   Geometry geometry = Geometry::New();
190   geometry.AddVertexBuffer( vertexPropertyBuffer );
191   if( indices.Size() > 0 )
192   {
193     geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
194   }
195
196
197   return geometry;
198 }
199
200 /**
201  * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
202  *
203  * @param[out] indices     The indices to add to
204  * @param[in]  rowIdx      The row index to start the quad
205  * @param[in]  nextRowIdx  The index to the next row
206  */
207 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
208 {
209   indices.PushBack( rowIdx );
210   indices.PushBack( nextRowIdx + 1 );
211   indices.PushBack( rowIdx + 1 );
212
213   indices.PushBack( rowIdx );
214   indices.PushBack( nextRowIdx );
215   indices.PushBack( nextRowIdx + 1 );
216 }
217
218 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
219 {
220   vertices.PushBack( Vector2( x, y ) );
221 }
222
223 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchLoader::StretchRanges& stretchPixels, uint16_t imageExtent)
224 {
225   uint16_t prevEnd = 0;
226   uint16_t prevFix = 0;
227   uint16_t prevStretch = 0;
228   unsigned int i = 1;
229   for( NPatchLoader::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
230   {
231     uint16_t start = it->GetX();
232     uint16_t end = it->GetY();
233
234     uint16_t fix = prevFix + start - prevEnd;
235     uint16_t stretch = prevStretch + end - start;
236
237     std::stringstream uniform;
238     uniform << uniformName << "[" << i << "]";
239     renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
240
241     prevEnd = end;
242     prevFix = fix;
243     prevStretch = stretch;
244   }
245
246   {
247     prevFix += imageExtent - prevEnd;
248     std::stringstream uniform;
249     uniform << uniformName << "[" << i << "]";
250     renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
251   }
252 }
253
254 } //unnamed namespace
255
256 /////////////////NPatchVisual////////////////
257
258 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl, const Property::Map& properties )
259 {
260   NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
261   nPatchVisual->mImageUrl = imageUrl;
262   nPatchVisual->SetProperties( properties );
263
264   return nPatchVisual;
265 }
266
267 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl )
268 {
269   NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
270   nPatchVisual->mImageUrl = imageUrl;
271
272   return nPatchVisual;
273 }
274
275 void NPatchVisual::LoadImages()
276 {
277   TextureManager& textureManager = mFactoryCache.GetTextureManager();
278   bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
279
280   if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocalResource() )
281   {
282     bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
283     mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
284
285     const NPatchLoader::Data* data;
286     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
287     {
288       EnablePreMultipliedAlpha( preMultiplyOnLoad );
289     }
290   }
291
292   if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
293   {
294     // Load the auxiliary image
295     auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
296     mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
297                                                             SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
298                                                             this, true, preMultiplyOnLoading );
299   }
300 }
301
302 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
303 {
304   naturalSize.x = 0u;
305   naturalSize.y = 0u;
306
307   // load now if not already loaded
308   const NPatchLoader::Data* data;
309   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
310   {
311     naturalSize.x = data->croppedWidth;
312     naturalSize.y = data->croppedHeight;
313   }
314   else
315   {
316     if( mImageUrl.IsValid() )
317     {
318       ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
319       if( dimensions != ImageDimensions( 0, 0 ) )
320       {
321         naturalSize.x = dimensions.GetWidth();
322         naturalSize.y = dimensions.GetHeight();
323       }
324     }
325   }
326
327   if( mAuxiliaryPixelBuffer )
328   {
329     naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) );
330     naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) );
331   }
332 }
333
334 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
335 {
336   // URL is already passed in via constructor
337
338   Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
339   if( borderOnlyValue )
340   {
341     borderOnlyValue->Get( mBorderOnly );
342   }
343
344   Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER );
345   if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
346   {
347     // Not a rect so try vector4
348     Vector4 border;
349     if( borderValue->Get( border ) )
350     {
351       mBorder.left = static_cast< int >( border.x );
352       mBorder.right = static_cast< int >( border.y );
353       mBorder.bottom = static_cast< int >( border.z );
354       mBorder.top = static_cast< int >( border.w );
355     }
356   }
357
358   Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME );
359   if( auxImage )
360   {
361     std::string url;
362     if( auxImage->Get( url ) )
363     {
364       mAuxiliaryUrl = url;
365     }
366   }
367
368   Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME );
369   if( auxImageAlpha )
370   {
371     auxImageAlpha->Get( mAuxiliaryImageAlpha );
372   }
373
374   Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
375   if( synchronousLoading )
376   {
377     bool sync = false;
378     synchronousLoading->Get( sync );
379     if( sync )
380     {
381       mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
382     }
383     else
384     {
385       mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
386     }
387   }
388 }
389
390 void NPatchVisual::DoSetOnStage( Actor& actor )
391 {
392   // load when first go on stage
393   LoadImages();
394
395   const NPatchLoader::Data* data;
396   if( mLoader.GetNPatchData( mId, data ) )
397   {
398     Geometry geometry = CreateGeometry();
399     Shader shader = CreateShader();
400
401     mImpl->mRenderer = Renderer::New( geometry, shader );
402
403     mPlacementActor = actor;
404     if( data->loadCompleted )
405     {
406       ApplyTextureAndUniforms();
407       actor.AddRenderer( mImpl->mRenderer );
408       mPlacementActor.Reset();
409
410       // npatch loaded and ready to display
411       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
412     }
413   }
414 }
415
416 void NPatchVisual::DoSetOffStage( Actor& actor )
417 {
418   actor.RemoveRenderer( mImpl->mRenderer );
419   mImpl->mRenderer.Reset();
420   mPlacementActor.Reset();
421 }
422
423 void NPatchVisual::OnSetTransform()
424 {
425   if( mImpl->mRenderer )
426   {
427     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
428   }
429 }
430
431 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
432 {
433   map.Clear();
434   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
435   map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
436   map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
437   map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder );
438
439   if( mAuxiliaryUrl.IsValid() )
440   {
441     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
442     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
443   }
444 }
445
446 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
447 {
448   if( mAuxiliaryUrl.IsValid() )
449   {
450     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
451     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
452   }
453 }
454
455 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
456 : Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH ),
457   mPlacementActor(),
458   mLoader( factoryCache.GetNPatchLoader() ),
459   mImageUrl(),
460   mAuxiliaryUrl(),
461   mId( NPatchLoader::UNINITIALIZED_ID ),
462   mBorderOnly( false ),
463   mBorder(),
464   mAuxiliaryImageAlpha( 0.0f )
465 {
466   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
467 }
468
469 NPatchVisual::~NPatchVisual()
470 {
471 }
472
473 Geometry NPatchVisual::CreateGeometry()
474 {
475   Geometry geometry;
476   const NPatchLoader::Data* data;
477   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
478   {
479     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
480     {
481       if( DALI_UNLIKELY( mBorderOnly ) )
482       {
483         geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
484       }
485       else
486       {
487         geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
488       }
489     }
490     else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
491     {
492       Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1,  2 * data->stretchPixelsY.Size() + 1 );
493       geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
494     }
495   }
496   else
497   {
498     // no N patch data so use default geometry
499     geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
500   }
501   return geometry;
502 }
503
504 Shader NPatchVisual::CreateShader()
505 {
506   Shader shader;
507   const NPatchLoader::Data* data;
508   // 0 is either no data (load failed?) or no stretch regions on image
509   // for both cases we use the default shader
510   NPatchLoader::StretchRanges::SizeType xStretchCount = 0;
511   NPatchLoader::StretchRanges::SizeType yStretchCount = 0;
512
513   auto fragmentShader = mAuxiliaryPixelBuffer ? FRAGMENT_MASK_SHADER
514                                               : FRAGMENT_SHADER;
515   auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
516                                           : VisualFactoryCache::NINE_PATCH_SHADER;
517
518   // ask loader for the regions
519   if( mLoader.GetNPatchData( mId, data ) )
520   {
521     xStretchCount = data->stretchPixelsX.Count();
522     yStretchCount = data->stretchPixelsY.Count();
523   }
524
525   if( DALI_LIKELY( !mImpl->mCustomShader ) )
526   {
527     if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
528                      ( xStretchCount == 0 && yStretchCount == 0 ) ) )
529     {
530       shader = mFactoryCache.GetShader( shaderType );
531       if( DALI_UNLIKELY( !shader ) )
532       {
533         shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader );
534         // Only cache vanilla 9 patch shaders
535         mFactoryCache.SaveShader( shaderType, shader );
536       }
537     }
538     else if( xStretchCount > 0 || yStretchCount > 0)
539     {
540       std::stringstream vertexShader;
541       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
542                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
543                    << VERTEX_SHADER;
544
545       shader = Shader::New( vertexShader.str(), fragmentShader );
546     }
547   }
548   else
549   {
550     Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
551
552     if( !mImpl->mCustomShader->mFragmentShader.empty() )
553     {
554       fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
555     }
556     hints = mImpl->mCustomShader->mHints;
557
558     /* Apply Custom Vertex Shader only if image is 9-patch */
559     if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
560         ( xStretchCount == 0 && yStretchCount == 0 ) )
561     {
562       const char* vertexShader = VERTEX_SHADER_3X3;
563
564       if( !mImpl->mCustomShader->mVertexShader.empty() )
565       {
566         vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
567       }
568       shader = Shader::New( vertexShader, fragmentShader, hints );
569     }
570     else if( xStretchCount > 0 || yStretchCount > 0)
571     {
572       std::stringstream vertexShader;
573       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
574                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
575                    << VERTEX_SHADER;
576
577       shader = Shader::New( vertexShader.str(), fragmentShader, hints );
578     }
579   }
580
581   return shader;
582 }
583
584 void NPatchVisual::ApplyTextureAndUniforms()
585 {
586   const NPatchLoader::Data* data;
587   TextureSet textureSet;
588
589   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
590   {
591     textureSet = data->textureSet;
592
593     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
594     {
595       //special case for 9 patch
596       Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
597       Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
598
599       uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0;
600       uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0;
601
602       mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
603       mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
604       mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
605       mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
606     }
607     else
608     {
609       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
610       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
611
612       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
613       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
614     }
615   }
616   else
617   {
618     DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
619     textureSet = TextureSet::New();
620
621     Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
622     textureSet.SetTexture( 0u, croppedImage );
623     mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
624     mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
625     mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
626     mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
627   }
628
629   if( mAuxiliaryPixelBuffer )
630   {
631     // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
632     // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
633     // on GL interpolation alone.
634     if( mAuxiliaryPixelBuffer.GetWidth() < data->croppedWidth &&
635         mAuxiliaryPixelBuffer.GetHeight() < data->croppedHeight )
636     {
637       mAuxiliaryPixelBuffer.Resize( data->croppedWidth, data->croppedHeight );
638     }
639
640     // Note, this resets mAuxiliaryPixelBuffer handle
641     auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer );
642
643     auto texture = Texture::New( TextureType::TEXTURE_2D,
644                                  auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(),
645                                  auxiliaryPixelData.GetHeight() );
646     texture.Upload( auxiliaryPixelData );
647     textureSet.SetTexture( 1, texture );
648     DevelHandle::RegisterProperty( mImpl->mRenderer, DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
649                                    AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
650   }
651   mImpl->mRenderer.SetTextures( textureSet );
652
653   // Register transform properties
654   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
655 }
656
657 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
658 {
659   Geometry geometry = mFactoryCache.GetGeometry( subType );
660   if( !geometry )
661   {
662     if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
663     {
664       geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
665     }
666     else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
667     {
668       geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
669     }
670     mFactoryCache.SaveGeometry( subType, geometry );
671   }
672   return geometry;
673 }
674
675 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
676 {
677   uint16_t gridWidth = gridSize.GetWidth();
678   uint16_t gridHeight = gridSize.GetHeight();
679
680   // Create vertices
681   Vector< Vector2 > vertices;
682   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
683
684   for( int y = 0; y < gridHeight + 1; ++y )
685   {
686     for( int x = 0; x < gridWidth + 1; ++x )
687     {
688       AddVertex( vertices, x, y );
689     }
690   }
691
692   // Create indices
693   Vector< unsigned short > indices;
694   indices.Reserve( gridWidth * gridHeight * 6 );
695
696   unsigned int rowIdx     = 0;
697   unsigned int nextRowIdx = gridWidth + 1;
698   for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
699   {
700     for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
701     {
702       AddQuadIndices( indices, rowIdx, nextRowIdx );
703     }
704   }
705
706   return GenerateGeometry( vertices, indices );
707 }
708
709 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
710 {
711   uint16_t gridWidth = gridSize.GetWidth();
712   uint16_t gridHeight = gridSize.GetHeight();
713
714   // Create vertices
715   Vector< Vector2 > vertices;
716   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
717
718   //top
719   int y = 0;
720   for(; y < 2; ++y)
721   {
722     for( int x = 0; x < gridWidth + 1; ++x )
723     {
724       AddVertex( vertices, x, y );
725     }
726   }
727
728   for(; y < gridHeight - 1; ++y)
729   {
730     //left
731     AddVertex( vertices, 0, y );
732     AddVertex( vertices, 1, y );
733
734     //right
735     AddVertex( vertices, gridWidth - 1, y );
736     AddVertex( vertices, gridWidth, y );
737   }
738
739   //bottom
740   for(; y < gridHeight + 1; ++y)
741   {
742     for( int x = 0; x < gridWidth + 1; ++x )
743     {
744       AddVertex( vertices, x, y );
745     }
746   }
747
748   // Create indices
749   Vector< unsigned short > indices;
750   indices.Reserve( gridWidth * gridHeight * 6 );
751
752   //top
753   unsigned int rowIdx     = 0 ;
754   unsigned int nextRowIdx = gridWidth + 1;
755   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
756   {
757     AddQuadIndices( indices, rowIdx, nextRowIdx );
758   }
759
760   if(gridHeight > 2)
761   {
762     rowIdx     = gridWidth + 1;
763     nextRowIdx = ( gridWidth + 1 ) * 2;
764
765     unsigned increment = gridWidth - 1;
766     if(gridHeight > 3)
767     {
768       increment = 2;
769       //second row left
770       AddQuadIndices( indices, rowIdx, nextRowIdx );
771
772       rowIdx     = gridWidth * 2;
773       nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
774       //second row right
775       AddQuadIndices( indices, rowIdx, nextRowIdx );
776
777       //left and right
778       rowIdx     = nextRowIdx - 2;
779       nextRowIdx = rowIdx + 4;
780       for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
781       {
782         AddQuadIndices( indices, rowIdx, nextRowIdx );
783       }
784     }
785
786     //second row left
787     AddQuadIndices( indices, rowIdx, nextRowIdx );
788
789     rowIdx     += increment;
790     nextRowIdx += gridWidth - 1;
791     //second row right
792     AddQuadIndices( indices, rowIdx, nextRowIdx );
793   }
794
795   //bottom
796   rowIdx     = nextRowIdx - gridWidth + 1;
797   nextRowIdx = rowIdx + gridWidth + 1;
798   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
799   {
800     AddQuadIndices( indices, rowIdx, nextRowIdx );
801   }
802
803   return GenerateGeometry( vertices, indices );
804 }
805
806 void NPatchVisual::SetResource()
807 {
808   const NPatchLoader::Data* data;
809   if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
810   {
811     Geometry geometry = CreateGeometry();
812     Shader shader = CreateShader();
813
814     mImpl->mRenderer.SetGeometry( geometry );
815     mImpl->mRenderer.SetShader( shader );
816
817     Actor actor = mPlacementActor.GetHandle();
818     if( actor )
819     {
820       ApplyTextureAndUniforms();
821       actor.AddRenderer( mImpl->mRenderer );
822       mPlacementActor.Reset();
823
824       // npatch loaded and ready to display
825       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
826     }
827   }
828 }
829
830 void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
831 {
832   if( url.GetUrl() == mAuxiliaryUrl.GetUrl() )
833   {
834     mAuxiliaryPixelBuffer = pixelBuffer;
835     const NPatchLoader::Data* data;
836     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
837     {
838       SetResource();
839     }
840   }
841   else
842   {
843     if( loadSuccess )
844     {
845       mLoader.SetNPatchData( mId, pixelBuffer );
846       EnablePreMultipliedAlpha( preMultiplied );
847     }
848
849     if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
850     {
851       SetResource();
852     }
853   }
854 }
855
856 } // namespace Internal
857
858 } // namespace Toolkit
859
860 } // namespace Dali