2 * Copyright (c) 2015 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-renderer.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>
27 #include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
28 #include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
29 #include <dali-toolkit/internal/controls/renderers/control-renderer-impl.h>
30 #include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
44 const char * const RENDERER_TYPE("rendererType");
45 const char * const RENDERER_TYPE_VALUE("nPatchRenderer");
47 const char * const IMAGE_URL_NAME("imageUrl");
48 const char * const BORDER_ONLY("borderOnly");
50 std::string TEXTURE_UNIFORM_NAME = "sTexture";
52 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
53 attribute mediump vec2 aPosition;\n
54 varying mediump vec2 vTexCoord;\n
55 uniform mediump mat4 uMvpMatrix;\n
56 uniform mediump vec3 uSize;\n
57 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
58 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
62 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
63 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
65 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
66 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
68 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( uSize.xy - fixedTotal ) * stretch / stretchTotal ), 0.0, 1.0 );\n
69 vertexPosition.xy -= uSize.xy * vec2( 0.5, 0.5 );\n
70 vertexPosition = uMvpMatrix * vertexPosition;\n
72 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
74 gl_Position = vertexPosition;\n
78 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
79 attribute mediump vec2 aPosition;\n
80 varying mediump vec2 vTexCoord;\n
81 uniform mediump mat4 uModelMatrix;\n
82 uniform mediump mat4 uMvpMatrix;\n
83 uniform mediump vec3 uSize;\n
84 uniform mediump vec2 uFixed[ 3 ];\n
85 uniform mediump vec2 uStretchTotal;\n
89 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
90 mediump vec2 size = uSize.xy * scale;\n
92 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
93 mediump vec2 stretch = floor( aPosition * 0.5 );\n
94 mediump vec2 fixedTotal = uFixed[ 2 ];\n
96 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
97 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
98 vertexPosition.xy = vertexPosition.xy / scale;\n
100 vertexPosition = uMvpMatrix * vertexPosition;\n
102 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
104 gl_Position = vertexPosition;\n
108 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
109 varying mediump vec2 vTexCoord;\n
110 uniform sampler2D sTexture;\n
111 uniform lowp vec4 uColor;\n
115 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
120 * @brief Creates the geometry formed from the vertices and indices
122 * @param[in] vertices The vertices to generate the geometry from
123 * @param[in] indices The indices to generate the geometry from
124 * @return The geometry formed from the vertices and indices
126 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned int >& indices )
128 Property::Map vertexFormat;
129 vertexFormat[ "aPosition" ] = Property::VECTOR2;
130 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat, vertices.Size() );
131 if( vertices.Size() > 0 )
133 vertexPropertyBuffer.SetData( &vertices[ 0 ] );
136 Property::Map indexFormat;
137 indexFormat[ "indices" ] = Property::INTEGER;
138 PropertyBuffer indexPropertyBuffer = PropertyBuffer::New( indexFormat, indices.Size() );
139 if( indices.Size() > 0 )
141 indexPropertyBuffer.SetData( &indices[ 0 ] );
144 // Create the geometry object
145 Geometry geometry = Geometry::New();
146 geometry.AddVertexBuffer( vertexPropertyBuffer );
147 geometry.SetIndexBuffer( indexPropertyBuffer );
153 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
155 * @param[out] indices The indices to add to
156 * @param[in] rowIdx The row index to start the quad
157 * @param[in] nextRowIdx The index to the next row
159 void AddQuadIndices( Vector< unsigned int >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
161 indices.PushBack( rowIdx );
162 indices.PushBack( nextRowIdx + 1 );
163 indices.PushBack( rowIdx + 1 );
165 indices.PushBack( rowIdx );
166 indices.PushBack( nextRowIdx );
167 indices.PushBack( nextRowIdx + 1 );
170 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
172 vertices.PushBack( Vector2( x, y ) );
175 void RegisterStretchProperties( Material& material, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
177 uint16_t prevEnd = 0;
178 uint16_t prevFix = 0;
179 uint16_t prevStretch = 0;
181 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
183 uint16_t start = it->GetX();
184 uint16_t end = it->GetY();
186 uint16_t fix = prevFix + start - prevEnd;
187 uint16_t stretch = prevStretch + end - start;
189 std::stringstream uniform;
190 uniform << uniformName << "[" << i << "]";
191 material.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
195 prevStretch = stretch;
199 prevFix += imageExtent - prevEnd;
200 std::stringstream uniform;
201 uniform << uniformName << "[" << i << "]";
202 material.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
206 } //unnamed namespace
208 /////////////////NPatchRenderer////////////////
210 NPatchRenderer::NPatchRenderer( RendererFactoryCache& factoryCache )
211 : ControlRenderer( factoryCache ),
216 NPatchRenderer::~NPatchRenderer()
220 void NPatchRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
222 Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
225 //Read the borderOnly property first since InitialiseFromImage relies on mBorderOnly to be properly set
226 Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
227 if( borderOnlyValue )
229 borderOnlyValue->Get( mBorderOnly );
232 if( imageURLValue->Get( mImageUrl ) )
234 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
235 InitializeFromImage( nPatch );
239 InitializeFromBrokenImage();
240 DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
245 void NPatchRenderer::GetNaturalSize( Vector2& naturalSize ) const
249 naturalSize.x = mImage.GetWidth();
250 naturalSize.y = mImage.GetHeight();
252 else if( !mImageUrl.empty() )
254 ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
255 naturalSize.x = dimentions.GetWidth();
256 naturalSize.y = dimentions.GetHeight();
260 naturalSize = Vector2::ZERO;
264 void NPatchRenderer::SetClipRect( const Rect<int>& clipRect )
266 ControlRenderer::SetClipRect( clipRect );
267 //ToDo: renderer responds to the clipRect change
270 void NPatchRenderer::SetOffset( const Vector2& offset )
272 //ToDo: renderer applies the offset
275 Geometry NPatchRenderer::CreateGeometry()
278 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
282 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY );
285 geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
286 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY, geometry );
291 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
294 geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
295 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
299 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
301 Uint16Pair gridSize( 2 * mStretchPixelsX.Size() + 1, 2 * mStretchPixelsY.Size() + 1 );
302 geometry = !mBorderOnly ? CreateGeometry( gridSize ) : CreateGeometryBorder( gridSize );
308 Shader NPatchRenderer::CreateShader()
311 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
313 shader = mFactoryCache.GetShader( RendererFactoryCache::NINE_PATCH_SHADER );
316 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
317 mFactoryCache.SaveShader( RendererFactoryCache::NINE_PATCH_SHADER, shader );
320 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
322 std::stringstream vertexShader;
323 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
324 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
327 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
332 void NPatchRenderer::InitializeRenderer()
334 Geometry geometry = CreateGeometry();
335 Shader shader = CreateShader();
337 if( !geometry || !shader )
339 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() );
340 InitializeFromBrokenImage();
343 Material material = Material::New( shader );
344 mImpl->mRenderer = Renderer::New( geometry, material );
348 void NPatchRenderer::DoSetOnStage( Actor& actor )
352 if( !mImageUrl.empty() )
354 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
355 InitializeFromImage( nPatch );
359 InitializeFromImage( mImage );
363 //initialize the renderer after initializing from the image since we need to know the grid size from the image before creating the geometry
364 InitializeRenderer();
368 ApplyImageToSampler();
372 void NPatchRenderer::DoSetOffStage( Actor& actor )
374 mCroppedImage.Reset();
377 void NPatchRenderer::DoCreatePropertyMap( Property::Map& map ) const
380 map.Insert( RENDERER_TYPE, RENDERER_TYPE_VALUE );
381 if( !mImageUrl.empty() )
383 map.Insert( IMAGE_URL_NAME, mImageUrl );
387 map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
389 map.Insert( BORDER_ONLY, mBorderOnly );
392 void NPatchRenderer::ChangeRenderer( bool oldBorderOnly, size_t oldGridX, size_t oldGridY )
394 //check to see if the border style has changed
396 bool borderOnlyChanged = oldBorderOnly != mBorderOnly;
397 bool gridChanged = oldGridX != mStretchPixelsX.Size() || oldGridY != mStretchPixelsY.Size();
399 if( borderOnlyChanged || gridChanged )
401 Geometry geometry = CreateGeometry();
404 mImpl->mRenderer.SetGeometry( geometry );
408 InitializeFromBrokenImage();
414 Shader shader = CreateShader();
418 material = mImpl->mRenderer.GetMaterial();
421 material.SetShader( shader );
427 InitializeFromBrokenImage();
432 void NPatchRenderer::SetImage( const std::string& imageUrl, bool borderOnly )
434 bool oldBorderOnly = mBorderOnly;
435 size_t oldGridX = mStretchPixelsX.Size();
436 size_t oldGridY = mStretchPixelsY.Size();
438 mBorderOnly = borderOnly;
440 if( mImageUrl == imageUrl )
445 mImageUrl = imageUrl;
446 if( mImpl->mRenderer )
448 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
449 InitializeFromImage( nPatch );
451 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
455 ApplyImageToSampler();
460 void NPatchRenderer::SetImage( NinePatchImage image, bool borderOnly )
462 bool oldBorderOnly = mBorderOnly;
463 size_t oldGridX = mStretchPixelsX.Size();
464 size_t oldGridY = mStretchPixelsY.Size();
466 mBorderOnly = borderOnly;
468 if( mImage == image )
474 if( mImpl->mRenderer )
476 InitializeFromImage( mImage );
477 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
481 ApplyImageToSampler();
486 void NPatchRenderer::InitializeFromImage( NinePatchImage nPatch )
488 mCroppedImage = nPatch.CreateCroppedBufferImage();
491 DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
492 InitializeFromBrokenImage();
496 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
498 mStretchPixelsX = nPatch.GetStretchPixelsX();
499 mStretchPixelsY = nPatch.GetStretchPixelsY();
502 void NPatchRenderer::InitializeFromBrokenImage()
504 mCroppedImage = RendererFactory::GetBrokenRendererImage();
505 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
507 mStretchPixelsX.Clear();
508 mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
509 mStretchPixelsY.Clear();
510 mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
513 void NPatchRenderer::ApplyImageToSampler()
515 Material material = mImpl->mRenderer.GetMaterial();
518 int index = material.GetTextureIndex( TEXTURE_UNIFORM_NAME );
521 material.SetTextureImage( index, mCroppedImage );
525 material.AddTexture( mCroppedImage, TEXTURE_UNIFORM_NAME );
528 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
530 //special case for 9 patch
531 Uint16Pair stretchX = mStretchPixelsX[ 0 ];
532 Uint16Pair stretchY = mStretchPixelsY[ 0 ];
534 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
535 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
537 material.RegisterProperty( "uFixed[0]", Vector2::ZERO );
538 material.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
539 material.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
540 material.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
544 material.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
545 material.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
547 RegisterStretchProperties( material, "uNinePatchFactorsX", mStretchPixelsX, mImageSize.GetWidth() );
548 RegisterStretchProperties( material, "uNinePatchFactorsY", mStretchPixelsY, mImageSize.GetHeight() );
553 Geometry NPatchRenderer::CreateGeometry( Uint16Pair gridSize )
555 uint16_t gridWidth = gridSize.GetWidth();
556 uint16_t gridHeight = gridSize.GetHeight();
559 Vector< Vector2 > vertices;
560 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
562 for( int y = 0; y < gridHeight + 1; ++y )
564 for( int x = 0; x < gridWidth + 1; ++x )
566 AddVertex( vertices, x, y );
571 //TODO: compare performance with triangle strip when Geometry supports it
572 Vector< unsigned int > indices;
573 indices.Reserve( gridWidth * gridHeight * 6 );
575 unsigned int rowIdx = 0;
576 unsigned int nextRowIdx = gridWidth + 1;
577 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
579 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
581 AddQuadIndices( indices, rowIdx, nextRowIdx );
585 return GenerateGeometry( vertices, indices );
588 Geometry NPatchRenderer::CreateGeometryBorder( Uint16Pair gridSize )
590 uint16_t gridWidth = gridSize.GetWidth();
591 uint16_t gridHeight = gridSize.GetHeight();
594 Vector< Vector2 > vertices;
595 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
601 for( int x = 0; x < gridWidth + 1; ++x )
603 AddVertex( vertices, x, y );
607 for(; y < gridHeight - 1; ++y)
610 AddVertex( vertices, 0, y );
611 AddVertex( vertices, 1, y );
614 AddVertex( vertices, gridWidth - 1, y );
615 AddVertex( vertices, gridWidth, y );
619 for(; y < gridHeight + 1; ++y)
621 for( int x = 0; x < gridWidth + 1; ++x )
623 AddVertex( vertices, x, y );
628 //TODO: compare performance with triangle strip when Geometry supports it
629 Vector< unsigned int > indices;
630 indices.Reserve( gridWidth * gridHeight * 6 );
633 unsigned int rowIdx = 0 ;
634 unsigned int nextRowIdx = gridWidth + 1;
635 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
637 AddQuadIndices( indices, rowIdx, nextRowIdx );
642 rowIdx = gridWidth + 1;
643 nextRowIdx = ( gridWidth + 1 ) * 2;
645 unsigned increment = gridWidth - 1;
650 AddQuadIndices( indices, rowIdx, nextRowIdx );
652 rowIdx = gridWidth * 2;
653 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
655 AddQuadIndices( indices, rowIdx, nextRowIdx );
658 rowIdx = nextRowIdx - 2;
659 nextRowIdx = rowIdx + 4;
660 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
662 AddQuadIndices( indices, rowIdx, nextRowIdx );
667 AddQuadIndices( indices, rowIdx, nextRowIdx );
670 nextRowIdx += gridWidth - 1;
672 AddQuadIndices( indices, rowIdx, nextRowIdx );
676 rowIdx = nextRowIdx - gridWidth + 1;
677 nextRowIdx = rowIdx + gridWidth + 1;
678 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
680 AddQuadIndices( indices, rowIdx, nextRowIdx );
683 return GenerateGeometry( vertices, indices );
686 } // namespace Internal
688 } // namespace Toolkit