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