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/internal/visuals/visual-factory-impl.h>
29 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
30 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
31 #include <dali-toolkit/internal/visuals/visual-impl.h>
32 #include <dali-toolkit/internal/visuals/visual-data-impl.h>
46 const char * const BORDER_ONLY("borderOnly");
48 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
49 attribute mediump vec2 aPosition;\n
50 varying mediump vec2 vTexCoord;\n
51 uniform mediump mat4 uMvpMatrix;\n
52 uniform mediump vec3 uSize;\n
53 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
54 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
58 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
59 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
61 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
62 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
64 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( uSize.xy - fixedTotal ) * stretch / stretchTotal ), 0.0, 1.0 );\n
65 vertexPosition.xy -= uSize.xy * vec2( 0.5, 0.5 );\n
66 vertexPosition = uMvpMatrix * vertexPosition;\n
68 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
70 gl_Position = vertexPosition;\n
74 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
75 attribute mediump vec2 aPosition;\n
76 varying mediump vec2 vTexCoord;\n
77 uniform mediump mat4 uModelMatrix;\n
78 uniform mediump mat4 uMvpMatrix;\n
79 uniform mediump vec3 uSize;\n
80 uniform mediump vec2 uFixed[ 3 ];\n
81 uniform mediump vec2 uStretchTotal;\n
85 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
86 mediump vec2 size = uSize.xy * scale;\n
88 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
89 mediump vec2 stretch = floor( aPosition * 0.5 );\n
90 mediump vec2 fixedTotal = uFixed[ 2 ];\n
92 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
93 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
94 vertexPosition.xy = vertexPosition.xy / scale;\n
96 vertexPosition = uMvpMatrix * vertexPosition;\n
98 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
100 gl_Position = vertexPosition;\n
104 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
105 varying mediump vec2 vTexCoord;\n
106 uniform sampler2D sTexture;\n
107 uniform lowp vec4 uColor;\n
111 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
116 * @brief Creates the geometry formed from the vertices and indices
118 * @param[in] vertices The vertices to generate the geometry from
119 * @param[in] indices The indices to generate the geometry from
120 * @return The geometry formed from the vertices and indices
122 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
124 Property::Map vertexFormat;
125 vertexFormat[ "aPosition" ] = Property::VECTOR2;
126 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
127 if( vertices.Size() > 0 )
129 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
132 // Create the geometry object
133 Geometry geometry = Geometry::New();
134 geometry.AddVertexBuffer( vertexPropertyBuffer );
135 if( indices.Size() > 0 )
137 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
145 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
147 * @param[out] indices The indices to add to
148 * @param[in] rowIdx The row index to start the quad
149 * @param[in] nextRowIdx The index to the next row
151 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
153 indices.PushBack( rowIdx );
154 indices.PushBack( nextRowIdx + 1 );
155 indices.PushBack( rowIdx + 1 );
157 indices.PushBack( rowIdx );
158 indices.PushBack( nextRowIdx );
159 indices.PushBack( nextRowIdx + 1 );
162 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
164 vertices.PushBack( Vector2( x, y ) );
167 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
169 uint16_t prevEnd = 0;
170 uint16_t prevFix = 0;
171 uint16_t prevStretch = 0;
173 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
175 uint16_t start = it->GetX();
176 uint16_t end = it->GetY();
178 uint16_t fix = prevFix + start - prevEnd;
179 uint16_t stretch = prevStretch + end - start;
181 std::stringstream uniform;
182 uniform << uniformName << "[" << i << "]";
183 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
187 prevStretch = stretch;
191 prevFix += imageExtent - prevEnd;
192 std::stringstream uniform;
193 uniform << uniformName << "[" << i << "]";
194 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
198 } //unnamed namespace
200 /////////////////NPatchVisual////////////////
202 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
203 : Visual( factoryCache ),
208 NPatchVisual::~NPatchVisual()
212 void NPatchVisual::DoInitialize( Actor& actor, const Property::Map& propertyMap )
214 Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
217 //Read the borderOnly property first since InitialiseFromImage relies on mBorderOnly to be properly set
218 Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
219 if( borderOnlyValue )
221 borderOnlyValue->Get( mBorderOnly );
224 if( imageURLValue->Get( mImageUrl ) )
226 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
227 InitializeFromImage( nPatch );
231 InitializeFromBrokenImage();
232 DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
237 void NPatchVisual::GetNaturalSize( Vector2& naturalSize ) const
241 naturalSize.x = mImage.GetWidth();
242 naturalSize.y = mImage.GetHeight();
244 else if( !mImageUrl.empty() )
246 ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
247 naturalSize.x = dimentions.GetWidth();
248 naturalSize.y = dimentions.GetHeight();
252 naturalSize = Vector2::ZERO;
256 void NPatchVisual::SetClipRect( const Rect<int>& clipRect )
258 Visual::SetClipRect( clipRect );
259 //ToDo: renderer responds to the clipRect change
262 void NPatchVisual::SetOffset( const Vector2& offset )
264 //ToDo: renderer applies the offset
267 Geometry NPatchVisual::CreateGeometry()
270 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
274 geometry = mFactoryCache.GetGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
277 geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
278 mFactoryCache.SaveGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY, geometry );
283 geometry = mFactoryCache.GetGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
286 geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
287 mFactoryCache.SaveGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
291 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
293 Uint16Pair gridSize( 2 * mStretchPixelsX.Size() + 1, 2 * mStretchPixelsY.Size() + 1 );
294 geometry = !mBorderOnly ? CreateGeometry( gridSize ) : CreateGeometryBorder( gridSize );
300 Shader NPatchVisual::CreateShader()
303 if( !mImpl->mCustomShader )
305 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
307 shader = mFactoryCache.GetShader( VisualFactoryCache::NINE_PATCH_SHADER );
310 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
311 mFactoryCache.SaveShader( VisualFactoryCache::NINE_PATCH_SHADER, shader );
314 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
316 std::stringstream vertexShader;
317 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
318 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
321 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
326 const char* fragmentShader = FRAGMENT_SHADER;
327 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
329 if( !mImpl->mCustomShader->mFragmentShader.empty() )
331 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
333 hints = mImpl->mCustomShader->mHints;
335 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
337 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
339 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
341 std::stringstream vertexShader;
342 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
343 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
346 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
353 void NPatchVisual::InitializeRenderer()
355 Geometry geometry = CreateGeometry();
356 Shader shader = CreateShader();
358 if( !geometry || !shader )
360 DALI_LOG_ERROR("The 9 patch image '%s' doesn't have any valid stretch borders and so is not a valid 9 patch image\n", mImageUrl.c_str() );
361 InitializeFromBrokenImage();
364 TextureSet textureSet = TextureSet::New();
365 mImpl->mRenderer = Renderer::New( geometry, shader );
366 mImpl->mRenderer.SetTextures( textureSet );
370 void NPatchVisual::DoSetOnStage( Actor& actor )
374 if( !mImageUrl.empty() )
376 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
377 InitializeFromImage( nPatch );
381 InitializeFromImage( mImage );
385 //initialize the renderer after initializing from the image since we need to know the grid size from the image before creating the geometry
386 InitializeRenderer();
390 ApplyImageToSampler();
394 void NPatchVisual::DoSetOffStage( Actor& actor )
396 mCroppedImage.Reset();
397 actor.RemoveRenderer( mImpl->mRenderer );
398 mImpl->mRenderer.Reset();
401 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
404 map.Insert( RENDERER_TYPE, IMAGE_RENDERER );
405 if( !mImageUrl.empty() )
407 map.Insert( IMAGE_URL_NAME, mImageUrl );
411 map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
413 map.Insert( BORDER_ONLY, mBorderOnly );
416 void NPatchVisual::ChangeRenderer( bool oldBorderOnly, size_t oldGridX, size_t oldGridY )
418 //check to see if the border style has changed
420 bool borderOnlyChanged = oldBorderOnly != mBorderOnly;
421 bool gridChanged = oldGridX != mStretchPixelsX.Size() || oldGridY != mStretchPixelsY.Size();
423 if( borderOnlyChanged || gridChanged )
425 Geometry geometry = CreateGeometry();
428 mImpl->mRenderer.SetGeometry( geometry );
432 InitializeFromBrokenImage();
438 Shader shader = CreateShader();
439 TextureSet textureSet;
442 textureSet = mImpl->mRenderer.GetTextures();
445 InitializeFromBrokenImage();
447 mImpl->mRenderer.SetShader( shader );
452 void NPatchVisual::SetImage( const std::string& imageUrl, bool borderOnly )
454 bool oldBorderOnly = mBorderOnly;
455 size_t oldGridX = mStretchPixelsX.Size();
456 size_t oldGridY = mStretchPixelsY.Size();
458 mBorderOnly = borderOnly;
460 if( mImageUrl == imageUrl )
465 mImageUrl = imageUrl;
466 if( mImpl->mRenderer )
468 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
469 InitializeFromImage( nPatch );
471 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
475 ApplyImageToSampler();
480 void NPatchVisual::SetImage( NinePatchImage image, bool borderOnly )
482 bool oldBorderOnly = mBorderOnly;
483 size_t oldGridX = mStretchPixelsX.Size();
484 size_t oldGridY = mStretchPixelsY.Size();
486 mBorderOnly = borderOnly;
488 if( mImage == image )
494 if( mImpl->mRenderer )
496 InitializeFromImage( mImage );
497 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
501 ApplyImageToSampler();
506 void NPatchVisual::InitializeFromImage( NinePatchImage nPatch )
508 mCroppedImage = nPatch.CreateCroppedBufferImage();
511 DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
512 InitializeFromBrokenImage();
516 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
518 mStretchPixelsX = nPatch.GetStretchPixelsX();
519 mStretchPixelsY = nPatch.GetStretchPixelsY();
522 void NPatchVisual::InitializeFromBrokenImage()
524 mCroppedImage = VisualFactory::GetBrokenRendererImage();
525 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
527 mStretchPixelsX.Clear();
528 mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
529 mStretchPixelsY.Clear();
530 mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
533 void NPatchVisual::ApplyImageToSampler()
535 TextureSet textureSet = mImpl->mRenderer.GetTextures();
538 TextureSetImage( textureSet, 0u, mCroppedImage );
540 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
542 //special case for 9 patch
543 Uint16Pair stretchX = mStretchPixelsX[ 0 ];
544 Uint16Pair stretchY = mStretchPixelsY[ 0 ];
546 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
547 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
549 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
550 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
551 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
552 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
556 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
557 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
559 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", mStretchPixelsX, mImageSize.GetWidth() );
560 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", mStretchPixelsY, mImageSize.GetHeight() );
565 Geometry NPatchVisual::CreateGeometry( Uint16Pair gridSize )
567 uint16_t gridWidth = gridSize.GetWidth();
568 uint16_t gridHeight = gridSize.GetHeight();
571 Vector< Vector2 > vertices;
572 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
574 for( int y = 0; y < gridHeight + 1; ++y )
576 for( int x = 0; x < gridWidth + 1; ++x )
578 AddVertex( vertices, x, y );
583 //TODO: compare performance with triangle strip when Geometry supports it
584 Vector< unsigned short > indices;
585 indices.Reserve( gridWidth * gridHeight * 6 );
587 unsigned int rowIdx = 0;
588 unsigned int nextRowIdx = gridWidth + 1;
589 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
591 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
593 AddQuadIndices( indices, rowIdx, nextRowIdx );
597 return GenerateGeometry( vertices, indices );
600 Geometry NPatchVisual::CreateGeometryBorder( Uint16Pair gridSize )
602 uint16_t gridWidth = gridSize.GetWidth();
603 uint16_t gridHeight = gridSize.GetHeight();
606 Vector< Vector2 > vertices;
607 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
613 for( int x = 0; x < gridWidth + 1; ++x )
615 AddVertex( vertices, x, y );
619 for(; y < gridHeight - 1; ++y)
622 AddVertex( vertices, 0, y );
623 AddVertex( vertices, 1, y );
626 AddVertex( vertices, gridWidth - 1, y );
627 AddVertex( vertices, gridWidth, y );
631 for(; y < gridHeight + 1; ++y)
633 for( int x = 0; x < gridWidth + 1; ++x )
635 AddVertex( vertices, x, y );
640 //TODO: compare performance with triangle strip when Geometry supports it
641 Vector< unsigned short > indices;
642 indices.Reserve( gridWidth * gridHeight * 6 );
645 unsigned int rowIdx = 0 ;
646 unsigned int nextRowIdx = gridWidth + 1;
647 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
649 AddQuadIndices( indices, rowIdx, nextRowIdx );
654 rowIdx = gridWidth + 1;
655 nextRowIdx = ( gridWidth + 1 ) * 2;
657 unsigned increment = gridWidth - 1;
662 AddQuadIndices( indices, rowIdx, nextRowIdx );
664 rowIdx = gridWidth * 2;
665 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
667 AddQuadIndices( indices, rowIdx, nextRowIdx );
670 rowIdx = nextRowIdx - 2;
671 nextRowIdx = rowIdx + 4;
672 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
674 AddQuadIndices( indices, rowIdx, nextRowIdx );
679 AddQuadIndices( indices, rowIdx, nextRowIdx );
682 nextRowIdx += gridWidth - 1;
684 AddQuadIndices( indices, rowIdx, nextRowIdx );
688 rowIdx = nextRowIdx - gridWidth + 1;
689 nextRowIdx = rowIdx + gridWidth + 1;
690 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
692 AddQuadIndices( indices, rowIdx, nextRowIdx );
695 return GenerateGeometry( vertices, indices );
698 } // namespace Internal
700 } // namespace Toolkit