2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "npatch-visual.h"
22 #include <dali/integration-api/platform-abstraction.h>
23 #include <dali/public-api/images/buffer-image.h>
24 #include <dali/public-api/images/resource-image.h>
25 #include <dali/devel-api/images/texture-set-image.h>
28 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
29 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
30 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
31 #include <dali-toolkit/internal/visuals/npatch-loader.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
33 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
34 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
35 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
36 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
50 const char * const BORDER_ONLY( "borderOnly" );
51 const char * const BORDER( "border" );
53 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
54 attribute mediump vec2 aPosition;\n
55 varying mediump vec2 vTexCoord;\n
56 uniform mediump mat4 uMvpMatrix;\n
57 uniform mediump vec3 uSize;\n
58 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
59 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
62 //Visual size and offset
63 uniform mediump vec2 offset;\n
64 uniform mediump vec2 size;\n
65 uniform mediump vec4 offsetSizeMode;\n
66 uniform mediump vec2 origin;\n
67 uniform mediump vec2 anchorPoint;\n
71 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
72 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
74 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
75 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
78 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
79 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
81 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal ) + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
82 vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
84 vertexPosition = uMvpMatrix * vertexPosition;\n
86 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
88 gl_Position = vertexPosition;\n
92 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
93 attribute mediump vec2 aPosition;\n
94 varying mediump vec2 vTexCoord;\n
95 uniform mediump mat4 uModelMatrix;\n
96 uniform mediump mat4 uMvpMatrix;\n
97 uniform mediump vec3 uSize;\n
98 uniform mediump vec2 uFixed[ 3 ];\n
99 uniform mediump vec2 uStretchTotal;\n
102 //Visual size and offset
103 uniform mediump vec2 offset;\n
104 uniform mediump vec2 size;\n
105 uniform mediump vec4 offsetSizeMode;\n
106 uniform mediump vec2 origin;\n
107 uniform mediump vec2 anchorPoint;\n
111 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
112 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
114 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
115 mediump vec2 size = visualSize.xy;\n
117 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
118 mediump vec2 stretch = floor( aPosition * 0.5 );\n
119 mediump vec2 fixedTotal = uFixed[ 2 ];\n
121 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );
122 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
123 vertexPosition.xy = vertexPosition.xy + anchorPoint*size + (visualOffset + origin)*uSize.xy;\
125 vertexPosition = uMvpMatrix * vertexPosition;\n
127 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
129 gl_Position = vertexPosition;\n
133 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
134 varying mediump vec2 vTexCoord;\n
135 uniform sampler2D sTexture;\n
136 uniform lowp vec4 uColor;\n
137 uniform lowp vec3 mixColor;\n
138 uniform lowp float opacity;\n
139 uniform lowp float preMultipliedAlpha;\n
140 lowp vec4 visualMixColor()\n
142 return vec4( mixColor * mix( 1.0, opacity, preMultipliedAlpha ), opacity );\n
146 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * visualMixColor();\n
151 * @brief Creates the geometry formed from the vertices and indices
153 * @param[in] vertices The vertices to generate the geometry from
154 * @param[in] indices The indices to generate the geometry from
155 * @return The geometry formed from the vertices and indices
157 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
159 Property::Map vertexFormat;
160 vertexFormat[ "aPosition" ] = Property::VECTOR2;
161 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
162 if( vertices.Size() > 0 )
164 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
167 // Create the geometry object
168 Geometry geometry = Geometry::New();
169 geometry.AddVertexBuffer( vertexPropertyBuffer );
170 if( indices.Size() > 0 )
172 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
180 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
182 * @param[out] indices The indices to add to
183 * @param[in] rowIdx The row index to start the quad
184 * @param[in] nextRowIdx The index to the next row
186 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
188 indices.PushBack( rowIdx );
189 indices.PushBack( nextRowIdx + 1 );
190 indices.PushBack( rowIdx + 1 );
192 indices.PushBack( rowIdx );
193 indices.PushBack( nextRowIdx );
194 indices.PushBack( nextRowIdx + 1 );
197 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
199 vertices.PushBack( Vector2( x, y ) );
202 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
204 uint16_t prevEnd = 0;
205 uint16_t prevFix = 0;
206 uint16_t prevStretch = 0;
208 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
210 uint16_t start = it->GetX();
211 uint16_t end = it->GetY();
213 uint16_t fix = prevFix + start - prevEnd;
214 uint16_t stretch = prevStretch + end - start;
216 std::stringstream uniform;
217 uniform << uniformName << "[" << i << "]";
218 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
222 prevStretch = stretch;
226 prevFix += imageExtent - prevEnd;
227 std::stringstream uniform;
228 uniform << uniformName << "[" << i << "]";
229 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
233 } //unnamed namespace
235 /////////////////NPatchVisual////////////////
237 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const std::string& imageUrl, const Property::Map& properties )
239 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
240 nPatchVisual->mImageUrl = imageUrl;
241 nPatchVisual->SetProperties( properties );
246 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const std::string& imageUrl )
248 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
249 nPatchVisual->mImageUrl = imageUrl;
254 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, NinePatchImage image )
256 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
257 nPatchVisual->mImageUrl = image.GetUrl();
262 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
266 // load now if not already loaded
267 if( NPatchLoader::UNINITIALIZED_ID == mId )
269 mId = mLoader.Load( mImageUrl, mBorder );
271 const NPatchLoader::Data* data;
272 if( mLoader.GetNPatchData( mId, data ) )
274 naturalSize.x = data->croppedWidth;
275 naturalSize.y = data->croppedHeight;
279 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
281 // URL is already passed in via constructor
283 Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
284 if( borderOnlyValue )
286 borderOnlyValue->Get( mBorderOnly );
289 Property::Value* borderValue = propertyMap.Find( Toolkit::DevelImageVisual::Property::BORDER, BORDER );
290 if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
292 // Not a rect so try vector4
294 if( borderValue->Get( border ) )
296 mBorder.left = static_cast< int >( border.x );
297 mBorder.right = static_cast< int >( border.y );
298 mBorder.bottom = static_cast< int >( border.z );
299 mBorder.top = static_cast< int >( border.w );
304 void NPatchVisual::DoSetOnStage( Actor& actor )
306 // load when first go on stage
307 if( NPatchLoader::UNINITIALIZED_ID == mId )
309 mId = mLoader.Load( mImageUrl, mBorder );
312 Geometry geometry = CreateGeometry();
313 Shader shader = CreateShader();
314 mImpl->mRenderer = Renderer::New( geometry, shader );
316 ApplyTextureAndUniforms();
318 actor.AddRenderer( mImpl->mRenderer );
321 void NPatchVisual::DoSetOffStage( Actor& actor )
323 actor.RemoveRenderer( mImpl->mRenderer );
324 mImpl->mRenderer.Reset();
327 void NPatchVisual::OnSetTransform()
329 if( mImpl->mRenderer )
331 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
335 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
338 map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::DevelVisual::N_PATCH );
339 map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl );
340 map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
341 map.Insert( Toolkit::DevelImageVisual::Property::BORDER, mBorder );
344 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
349 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
350 : Visual::Base( factoryCache ),
351 mLoader( factoryCache.GetNPatchLoader() ),
353 mId( NPatchLoader::UNINITIALIZED_ID ),
354 mBorderOnly( false ),
359 NPatchVisual::~NPatchVisual()
363 Geometry NPatchVisual::CreateGeometry()
366 const NPatchLoader::Data* data;
367 if( mLoader.GetNPatchData( mId, data ) )
369 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
371 if( DALI_UNLIKELY( mBorderOnly ) )
373 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
377 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
380 else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
382 Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1, 2 * data->stretchPixelsY.Size() + 1 );
383 geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
388 // no N patch data so use default geometry
389 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
394 Shader NPatchVisual::CreateShader()
397 const NPatchLoader::Data* data;
398 // 0 is either no data (load failed?) or no stretch regions on image
399 // for both cases we use the default shader
400 NinePatchImage::StretchRanges::SizeType xStretchCount = 0;
401 NinePatchImage::StretchRanges::SizeType yStretchCount = 0;
403 // ask loader for the regions
404 if( mLoader.GetNPatchData( mId, data ) )
406 xStretchCount = data->stretchPixelsX.Count();
407 yStretchCount = data->stretchPixelsY.Count();
410 if( DALI_LIKELY( !mImpl->mCustomShader ) )
412 if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
413 ( xStretchCount == 0 && yStretchCount == 0 ) ) )
415 shader = mFactoryCache.GetShader( VisualFactoryCache::NINE_PATCH_SHADER );
416 if( DALI_UNLIKELY( !shader ) )
418 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
419 mFactoryCache.SaveShader( VisualFactoryCache::NINE_PATCH_SHADER, shader );
422 else if( xStretchCount > 0 || yStretchCount > 0)
424 std::stringstream vertexShader;
425 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
426 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
429 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
434 const char* fragmentShader = FRAGMENT_SHADER;
435 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
437 if( !mImpl->mCustomShader->mFragmentShader.empty() )
439 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
441 hints = mImpl->mCustomShader->mHints;
443 if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
444 ( xStretchCount == 0 && yStretchCount == 0 ) )
446 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
448 else if( xStretchCount > 0 || yStretchCount > 0)
450 std::stringstream vertexShader;
451 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
452 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
455 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
462 void NPatchVisual::ApplyTextureAndUniforms()
464 const NPatchLoader::Data* data;
465 if( mLoader.GetNPatchData( mId, data ) )
467 TextureSet textures( data->textureSet );
468 mImpl->mRenderer.SetTextures( textures );
469 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
471 //special case for 9 patch
472 Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
473 Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
475 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
476 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
478 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
479 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
480 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
481 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
485 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
486 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
488 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
489 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
494 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.c_str() );
495 TextureSet textureSet = TextureSet::New();
496 mImpl->mRenderer.SetTextures( textureSet );
497 Image croppedImage = VisualFactoryCache::GetBrokenVisualImage();
498 TextureSetImage( textureSet, 0u, croppedImage );
499 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
500 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
501 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
502 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
505 //Register transform properties
506 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
509 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
511 Geometry geometry = mFactoryCache.GetGeometry( subType );
514 if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
516 geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
518 else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
520 geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
522 mFactoryCache.SaveGeometry( subType, geometry );
527 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
529 uint16_t gridWidth = gridSize.GetWidth();
530 uint16_t gridHeight = gridSize.GetHeight();
533 Vector< Vector2 > vertices;
534 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
536 for( int y = 0; y < gridHeight + 1; ++y )
538 for( int x = 0; x < gridWidth + 1; ++x )
540 AddVertex( vertices, x, y );
545 Vector< unsigned short > indices;
546 indices.Reserve( gridWidth * gridHeight * 6 );
548 unsigned int rowIdx = 0;
549 unsigned int nextRowIdx = gridWidth + 1;
550 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
552 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
554 AddQuadIndices( indices, rowIdx, nextRowIdx );
558 return GenerateGeometry( vertices, indices );
561 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
563 uint16_t gridWidth = gridSize.GetWidth();
564 uint16_t gridHeight = gridSize.GetHeight();
567 Vector< Vector2 > vertices;
568 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
574 for( int x = 0; x < gridWidth + 1; ++x )
576 AddVertex( vertices, x, y );
580 for(; y < gridHeight - 1; ++y)
583 AddVertex( vertices, 0, y );
584 AddVertex( vertices, 1, y );
587 AddVertex( vertices, gridWidth - 1, y );
588 AddVertex( vertices, gridWidth, y );
592 for(; y < gridHeight + 1; ++y)
594 for( int x = 0; x < gridWidth + 1; ++x )
596 AddVertex( vertices, x, y );
601 Vector< unsigned short > indices;
602 indices.Reserve( gridWidth * gridHeight * 6 );
605 unsigned int rowIdx = 0 ;
606 unsigned int nextRowIdx = gridWidth + 1;
607 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
609 AddQuadIndices( indices, rowIdx, nextRowIdx );
614 rowIdx = gridWidth + 1;
615 nextRowIdx = ( gridWidth + 1 ) * 2;
617 unsigned increment = gridWidth - 1;
622 AddQuadIndices( indices, rowIdx, nextRowIdx );
624 rowIdx = gridWidth * 2;
625 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
627 AddQuadIndices( indices, rowIdx, nextRowIdx );
630 rowIdx = nextRowIdx - 2;
631 nextRowIdx = rowIdx + 4;
632 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
634 AddQuadIndices( indices, rowIdx, nextRowIdx );
639 AddQuadIndices( indices, rowIdx, nextRowIdx );
642 nextRowIdx += gridWidth - 1;
644 AddQuadIndices( indices, rowIdx, nextRowIdx );
648 rowIdx = nextRowIdx - gridWidth + 1;
649 nextRowIdx = rowIdx + gridWidth + 1;
650 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
652 AddQuadIndices( indices, rowIdx, nextRowIdx );
655 return GenerateGeometry( vertices, indices );
658 } // namespace Internal
660 } // namespace Toolkit