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