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