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/internal/visuals/npatch-loader.h>
31 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
33 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
34 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
49 const char * const BORDER_ONLY("borderOnly");
51 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
52 attribute mediump vec2 aPosition;\n
53 varying mediump vec2 vTexCoord;\n
54 uniform mediump mat4 uMvpMatrix;\n
55 uniform mediump vec3 uSize;\n
56 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
57 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
60 //Visual size and offset
61 uniform mediump vec2 offset;\n
62 uniform mediump vec2 size;\n
63 uniform mediump vec4 offsetSizeMode;\n
64 uniform mediump vec2 origin;\n
65 uniform mediump vec2 anchorPoint;\n
69 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
70 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
72 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
73 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
76 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
77 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
79 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal ) + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
80 vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
82 vertexPosition = uMvpMatrix * vertexPosition;\n
84 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
86 gl_Position = vertexPosition;\n
90 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
91 attribute mediump vec2 aPosition;\n
92 varying mediump vec2 vTexCoord;\n
93 uniform mediump mat4 uModelMatrix;\n
94 uniform mediump mat4 uMvpMatrix;\n
95 uniform mediump vec3 uSize;\n
96 uniform mediump vec2 uFixed[ 3 ];\n
97 uniform mediump vec2 uStretchTotal;\n
100 //Visual size and offset
101 uniform mediump vec2 offset;\n
102 uniform mediump vec2 size;\n
103 uniform mediump vec4 offsetSizeMode;\n
104 uniform mediump vec2 origin;\n
105 uniform mediump vec2 anchorPoint;\n
109 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
110 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
112 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
113 mediump vec2 size = visualSize.xy;\n
115 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
116 mediump vec2 stretch = floor( aPosition * 0.5 );\n
117 mediump vec2 fixedTotal = uFixed[ 2 ];\n
119 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );
120 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
121 vertexPosition.xy = vertexPosition.xy + anchorPoint*size + (visualOffset + origin)*uSize.xy;\
123 vertexPosition = uMvpMatrix * vertexPosition;\n
125 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
127 gl_Position = vertexPosition;\n
131 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
132 varying mediump vec2 vTexCoord;\n
133 uniform sampler2D sTexture;\n
134 uniform lowp vec4 uColor;\n
135 uniform lowp vec3 mixColor;\n
136 uniform lowp float opacity;\n
137 uniform lowp float preMultipliedAlpha;\n
138 lowp vec4 visualMixColor()\n
140 return vec4( mixColor * mix( 1.0, opacity, preMultipliedAlpha ), opacity );\n
144 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * visualMixColor();\n
149 * @brief Creates the geometry formed from the vertices and indices
151 * @param[in] vertices The vertices to generate the geometry from
152 * @param[in] indices The indices to generate the geometry from
153 * @return The geometry formed from the vertices and indices
155 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
157 Property::Map vertexFormat;
158 vertexFormat[ "aPosition" ] = Property::VECTOR2;
159 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
160 if( vertices.Size() > 0 )
162 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
165 // Create the geometry object
166 Geometry geometry = Geometry::New();
167 geometry.AddVertexBuffer( vertexPropertyBuffer );
168 if( indices.Size() > 0 )
170 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
178 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
180 * @param[out] indices The indices to add to
181 * @param[in] rowIdx The row index to start the quad
182 * @param[in] nextRowIdx The index to the next row
184 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
186 indices.PushBack( rowIdx );
187 indices.PushBack( nextRowIdx + 1 );
188 indices.PushBack( rowIdx + 1 );
190 indices.PushBack( rowIdx );
191 indices.PushBack( nextRowIdx );
192 indices.PushBack( nextRowIdx + 1 );
195 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
197 vertices.PushBack( Vector2( x, y ) );
200 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
202 uint16_t prevEnd = 0;
203 uint16_t prevFix = 0;
204 uint16_t prevStretch = 0;
206 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
208 uint16_t start = it->GetX();
209 uint16_t end = it->GetY();
211 uint16_t fix = prevFix + start - prevEnd;
212 uint16_t stretch = prevStretch + end - start;
214 std::stringstream uniform;
215 uniform << uniformName << "[" << i << "]";
216 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
220 prevStretch = stretch;
224 prevFix += imageExtent - prevEnd;
225 std::stringstream uniform;
226 uniform << uniformName << "[" << i << "]";
227 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
231 } //unnamed namespace
233 /////////////////NPatchVisual////////////////
235 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const std::string& imageUrl, const Property::Map& properties )
237 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
238 nPatchVisual->mImageUrl = imageUrl;
239 nPatchVisual->SetProperties( properties );
244 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const std::string& imageUrl )
246 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
247 nPatchVisual->mImageUrl = imageUrl;
252 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, NinePatchImage image )
254 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
255 nPatchVisual->mImageUrl = image.GetUrl();
260 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
264 // load now if not already loaded
265 if( NPatchLoader::UNINITIALIZED_ID == mId )
267 mId = mLoader.Load( mImageUrl );
269 const NPatchLoader::Data* data;
270 if( mLoader.GetNPatchData( mId, data ) )
272 naturalSize.x = data->croppedWidth;
273 naturalSize.y = data->croppedHeight;
277 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
279 // URL is already passed in via constructor
281 Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
282 if( borderOnlyValue )
284 borderOnlyValue->Get( mBorderOnly );
288 void NPatchVisual::DoSetOnStage( Actor& actor )
290 // load when first go on stage
291 if( NPatchLoader::UNINITIALIZED_ID == mId )
293 mId = mLoader.Load( mImageUrl );
296 Geometry geometry = CreateGeometry();
297 Shader shader = CreateShader();
298 mImpl->mRenderer = Renderer::New( geometry, shader );
300 ApplyTextureAndUniforms();
302 actor.AddRenderer( mImpl->mRenderer );
305 void NPatchVisual::DoSetOffStage( Actor& actor )
307 actor.RemoveRenderer( mImpl->mRenderer );
308 mImpl->mRenderer.Reset();
311 void NPatchVisual::OnSetTransform()
313 if( mImpl->mRenderer )
315 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
319 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
322 map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::Visual::IMAGE );
323 map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl );
324 map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
327 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
328 : Visual::Base( factoryCache ),
329 mLoader( factoryCache.GetNPatchLoader() ),
331 mId( NPatchLoader::UNINITIALIZED_ID ),
336 NPatchVisual::~NPatchVisual()
340 Geometry NPatchVisual::CreateGeometry()
343 const NPatchLoader::Data* data;
344 if( mLoader.GetNPatchData( mId, data ) )
346 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
348 if( DALI_UNLIKELY( mBorderOnly ) )
350 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
354 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
357 else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
359 Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1, 2 * data->stretchPixelsY.Size() + 1 );
360 geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
365 // no N patch data so use default geometry
366 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
371 Shader NPatchVisual::CreateShader()
374 const NPatchLoader::Data* data;
375 // 0 is either no data (load failed?) or no stretch regions on image
376 // for both cases we use the default shader
377 NinePatchImage::StretchRanges::SizeType xStretchCount = 0;
378 NinePatchImage::StretchRanges::SizeType yStretchCount = 0;
380 // ask loader for the regions
381 if( mLoader.GetNPatchData( mId, data ) )
383 xStretchCount = data->stretchPixelsX.Count();
384 yStretchCount = data->stretchPixelsY.Count();
387 if( DALI_LIKELY( !mImpl->mCustomShader ) )
389 if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
390 ( xStretchCount == 0 && yStretchCount == 0 ) ) )
392 shader = mFactoryCache.GetShader( VisualFactoryCache::NINE_PATCH_SHADER );
393 if( DALI_UNLIKELY( !shader ) )
395 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
396 mFactoryCache.SaveShader( VisualFactoryCache::NINE_PATCH_SHADER, shader );
399 else if( xStretchCount > 0 || yStretchCount > 0)
401 std::stringstream vertexShader;
402 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
403 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
406 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
411 const char* fragmentShader = FRAGMENT_SHADER;
412 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
414 if( !mImpl->mCustomShader->mFragmentShader.empty() )
416 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
418 hints = mImpl->mCustomShader->mHints;
420 if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
421 ( xStretchCount == 0 && yStretchCount == 0 ) )
423 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
425 else if( xStretchCount > 0 || yStretchCount > 0)
427 std::stringstream vertexShader;
428 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
429 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
432 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
439 void NPatchVisual::ApplyTextureAndUniforms()
441 const NPatchLoader::Data* data;
442 if( mLoader.GetNPatchData( mId, data ) )
444 TextureSet textures( data->textureSet );
445 mImpl->mRenderer.SetTextures( textures );
446 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
448 //special case for 9 patch
449 Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
450 Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
452 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
453 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
455 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
456 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
457 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
458 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
462 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
463 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
465 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
466 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
471 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.c_str() );
472 TextureSet textureSet = TextureSet::New();
473 mImpl->mRenderer.SetTextures( textureSet );
474 Image croppedImage = VisualFactoryCache::GetBrokenVisualImage();
475 TextureSetImage( textureSet, 0u, croppedImage );
476 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
477 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
478 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
479 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
482 //Register transform properties
483 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
486 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
488 Geometry geometry = mFactoryCache.GetGeometry( subType );
491 if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
493 geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
495 else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
497 geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
499 mFactoryCache.SaveGeometry( subType, geometry );
504 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
506 uint16_t gridWidth = gridSize.GetWidth();
507 uint16_t gridHeight = gridSize.GetHeight();
510 Vector< Vector2 > vertices;
511 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
513 for( int y = 0; y < gridHeight + 1; ++y )
515 for( int x = 0; x < gridWidth + 1; ++x )
517 AddVertex( vertices, x, y );
522 Vector< unsigned short > indices;
523 indices.Reserve( gridWidth * gridHeight * 6 );
525 unsigned int rowIdx = 0;
526 unsigned int nextRowIdx = gridWidth + 1;
527 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
529 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
531 AddQuadIndices( indices, rowIdx, nextRowIdx );
535 return GenerateGeometry( vertices, indices );
538 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
540 uint16_t gridWidth = gridSize.GetWidth();
541 uint16_t gridHeight = gridSize.GetHeight();
544 Vector< Vector2 > vertices;
545 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
551 for( int x = 0; x < gridWidth + 1; ++x )
553 AddVertex( vertices, x, y );
557 for(; y < gridHeight - 1; ++y)
560 AddVertex( vertices, 0, y );
561 AddVertex( vertices, 1, y );
564 AddVertex( vertices, gridWidth - 1, y );
565 AddVertex( vertices, gridWidth, y );
569 for(; y < gridHeight + 1; ++y)
571 for( int x = 0; x < gridWidth + 1; ++x )
573 AddVertex( vertices, x, y );
578 Vector< unsigned short > indices;
579 indices.Reserve( gridWidth * gridHeight * 6 );
582 unsigned int rowIdx = 0 ;
583 unsigned int nextRowIdx = gridWidth + 1;
584 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
586 AddQuadIndices( indices, rowIdx, nextRowIdx );
591 rowIdx = gridWidth + 1;
592 nextRowIdx = ( gridWidth + 1 ) * 2;
594 unsigned increment = gridWidth - 1;
599 AddQuadIndices( indices, rowIdx, nextRowIdx );
601 rowIdx = gridWidth * 2;
602 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
604 AddQuadIndices( indices, rowIdx, nextRowIdx );
607 rowIdx = nextRowIdx - 2;
608 nextRowIdx = rowIdx + 4;
609 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
611 AddQuadIndices( indices, rowIdx, nextRowIdx );
616 AddQuadIndices( indices, rowIdx, nextRowIdx );
619 nextRowIdx += gridWidth - 1;
621 AddQuadIndices( indices, rowIdx, nextRowIdx );
625 rowIdx = nextRowIdx - gridWidth + 1;
626 nextRowIdx = rowIdx + gridWidth + 1;
627 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
629 AddQuadIndices( indices, rowIdx, nextRowIdx );
632 return GenerateGeometry( vertices, indices );
635 } // namespace Internal
637 } // namespace Toolkit