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/renderer-string-constants.h>
30 #include <dali-toolkit/internal/controls/renderers/control-renderer-impl.h>
31 #include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
45 const char * const BORDER_ONLY("borderOnly");
47 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
48 attribute mediump vec2 aPosition;\n
49 varying mediump vec2 vTexCoord;\n
50 uniform mediump mat4 uMvpMatrix;\n
51 uniform mediump vec3 uSize;\n
52 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
53 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
57 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
58 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
60 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
61 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
63 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( uSize.xy - fixedTotal ) * stretch / stretchTotal ), 0.0, 1.0 );\n
64 vertexPosition.xy -= uSize.xy * vec2( 0.5, 0.5 );\n
65 vertexPosition = uMvpMatrix * vertexPosition;\n
67 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
69 gl_Position = vertexPosition;\n
73 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
74 attribute mediump vec2 aPosition;\n
75 varying mediump vec2 vTexCoord;\n
76 uniform mediump mat4 uModelMatrix;\n
77 uniform mediump mat4 uMvpMatrix;\n
78 uniform mediump vec3 uSize;\n
79 uniform mediump vec2 uFixed[ 3 ];\n
80 uniform mediump vec2 uStretchTotal;\n
84 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
85 mediump vec2 size = uSize.xy * scale;\n
87 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
88 mediump vec2 stretch = floor( aPosition * 0.5 );\n
89 mediump vec2 fixedTotal = uFixed[ 2 ];\n
91 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
92 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
93 vertexPosition.xy = vertexPosition.xy / scale;\n
95 vertexPosition = uMvpMatrix * vertexPosition;\n
97 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
99 gl_Position = vertexPosition;\n
103 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
104 varying mediump vec2 vTexCoord;\n
105 uniform sampler2D sTexture;\n
106 uniform lowp vec4 uColor;\n
110 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
115 * @brief Creates the geometry formed from the vertices and indices
117 * @param[in] vertices The vertices to generate the geometry from
118 * @param[in] indices The indices to generate the geometry from
119 * @return The geometry formed from the vertices and indices
121 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
123 Property::Map vertexFormat;
124 vertexFormat[ "aPosition" ] = Property::VECTOR2;
125 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
126 if( vertices.Size() > 0 )
128 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
131 // Create the geometry object
132 Geometry geometry = Geometry::New();
133 geometry.AddVertexBuffer( vertexPropertyBuffer );
134 if( indices.Size() > 0 )
136 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
144 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
146 * @param[out] indices The indices to add to
147 * @param[in] rowIdx The row index to start the quad
148 * @param[in] nextRowIdx The index to the next row
150 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
152 indices.PushBack( rowIdx );
153 indices.PushBack( nextRowIdx + 1 );
154 indices.PushBack( rowIdx + 1 );
156 indices.PushBack( rowIdx );
157 indices.PushBack( nextRowIdx );
158 indices.PushBack( nextRowIdx + 1 );
161 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
163 vertices.PushBack( Vector2( x, y ) );
166 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
168 uint16_t prevEnd = 0;
169 uint16_t prevFix = 0;
170 uint16_t prevStretch = 0;
172 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
174 uint16_t start = it->GetX();
175 uint16_t end = it->GetY();
177 uint16_t fix = prevFix + start - prevEnd;
178 uint16_t stretch = prevStretch + end - start;
180 std::stringstream uniform;
181 uniform << uniformName << "[" << i << "]";
182 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
186 prevStretch = stretch;
190 prevFix += imageExtent - prevEnd;
191 std::stringstream uniform;
192 uniform << uniformName << "[" << i << "]";
193 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
197 } //unnamed namespace
199 /////////////////NPatchRenderer////////////////
201 NPatchRenderer::NPatchRenderer( RendererFactoryCache& factoryCache )
202 : ControlRenderer( factoryCache ),
207 NPatchRenderer::~NPatchRenderer()
211 void NPatchRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
213 Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
216 //Read the borderOnly property first since InitialiseFromImage relies on mBorderOnly to be properly set
217 Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
218 if( borderOnlyValue )
220 borderOnlyValue->Get( mBorderOnly );
223 if( imageURLValue->Get( mImageUrl ) )
225 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
226 InitializeFromImage( nPatch );
230 InitializeFromBrokenImage();
231 DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
236 void NPatchRenderer::GetNaturalSize( Vector2& naturalSize ) const
240 naturalSize.x = mImage.GetWidth();
241 naturalSize.y = mImage.GetHeight();
243 else if( !mImageUrl.empty() )
245 ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
246 naturalSize.x = dimentions.GetWidth();
247 naturalSize.y = dimentions.GetHeight();
251 naturalSize = Vector2::ZERO;
255 void NPatchRenderer::SetClipRect( const Rect<int>& clipRect )
257 ControlRenderer::SetClipRect( clipRect );
258 //ToDo: renderer responds to the clipRect change
261 void NPatchRenderer::SetOffset( const Vector2& offset )
263 //ToDo: renderer applies the offset
266 Geometry NPatchRenderer::CreateGeometry()
269 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
273 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY );
276 geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
277 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY, geometry );
282 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
285 geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
286 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
290 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
292 Uint16Pair gridSize( 2 * mStretchPixelsX.Size() + 1, 2 * mStretchPixelsY.Size() + 1 );
293 geometry = !mBorderOnly ? CreateGeometry( gridSize ) : CreateGeometryBorder( gridSize );
299 Shader NPatchRenderer::CreateShader()
302 if( !mImpl->mCustomShader )
304 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
306 shader = mFactoryCache.GetShader( RendererFactoryCache::NINE_PATCH_SHADER );
309 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
310 mFactoryCache.SaveShader( RendererFactoryCache::NINE_PATCH_SHADER, shader );
313 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
315 std::stringstream vertexShader;
316 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
317 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
320 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
325 const char* fragmentShader = FRAGMENT_SHADER;
326 Dali::Shader::ShaderHints hints = Dali::Shader::HINT_NONE;
328 if( !mImpl->mCustomShader->mFragmentShader.empty() )
330 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
332 hints = mImpl->mCustomShader->mHints;
334 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
336 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
338 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
340 std::stringstream vertexShader;
341 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
342 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
345 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
352 void NPatchRenderer::InitializeRenderer()
354 Geometry geometry = CreateGeometry();
355 Shader shader = CreateShader();
357 if( !geometry || !shader )
359 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() );
360 InitializeFromBrokenImage();
363 TextureSet textureSet = TextureSet::New();
364 mImpl->mRenderer = Renderer::New( geometry, shader );
365 mImpl->mRenderer.SetTextures( textureSet );
369 void NPatchRenderer::DoSetOnStage( Actor& actor )
373 if( !mImageUrl.empty() )
375 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
376 InitializeFromImage( nPatch );
380 InitializeFromImage( mImage );
384 //initialize the renderer after initializing from the image since we need to know the grid size from the image before creating the geometry
385 InitializeRenderer();
389 ApplyImageToSampler();
393 void NPatchRenderer::DoSetOffStage( Actor& actor )
395 mCroppedImage.Reset();
396 actor.RemoveRenderer( mImpl->mRenderer );
397 mImpl->mRenderer.Reset();
400 void NPatchRenderer::DoCreatePropertyMap( Property::Map& map ) const
403 map.Insert( RENDERER_TYPE, IMAGE_RENDERER );
404 if( !mImageUrl.empty() )
406 map.Insert( IMAGE_URL_NAME, mImageUrl );
410 map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
412 map.Insert( BORDER_ONLY, mBorderOnly );
415 void NPatchRenderer::ChangeRenderer( bool oldBorderOnly, size_t oldGridX, size_t oldGridY )
417 //check to see if the border style has changed
419 bool borderOnlyChanged = oldBorderOnly != mBorderOnly;
420 bool gridChanged = oldGridX != mStretchPixelsX.Size() || oldGridY != mStretchPixelsY.Size();
422 if( borderOnlyChanged || gridChanged )
424 Geometry geometry = CreateGeometry();
427 mImpl->mRenderer.SetGeometry( geometry );
431 InitializeFromBrokenImage();
437 Shader shader = CreateShader();
438 TextureSet textureSet;
441 textureSet = mImpl->mRenderer.GetTextures();
444 InitializeFromBrokenImage();
446 mImpl->mRenderer.SetShader( shader );
451 void NPatchRenderer::SetImage( const std::string& imageUrl, bool borderOnly )
453 bool oldBorderOnly = mBorderOnly;
454 size_t oldGridX = mStretchPixelsX.Size();
455 size_t oldGridY = mStretchPixelsY.Size();
457 mBorderOnly = borderOnly;
459 if( mImageUrl == imageUrl )
464 mImageUrl = imageUrl;
465 if( mImpl->mRenderer )
467 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
468 InitializeFromImage( nPatch );
470 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
474 ApplyImageToSampler();
479 void NPatchRenderer::SetImage( NinePatchImage image, bool borderOnly )
481 bool oldBorderOnly = mBorderOnly;
482 size_t oldGridX = mStretchPixelsX.Size();
483 size_t oldGridY = mStretchPixelsY.Size();
485 mBorderOnly = borderOnly;
487 if( mImage == image )
493 if( mImpl->mRenderer )
495 InitializeFromImage( mImage );
496 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
500 ApplyImageToSampler();
505 void NPatchRenderer::InitializeFromImage( NinePatchImage nPatch )
507 mCroppedImage = nPatch.CreateCroppedBufferImage();
510 DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
511 InitializeFromBrokenImage();
515 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
517 mStretchPixelsX = nPatch.GetStretchPixelsX();
518 mStretchPixelsY = nPatch.GetStretchPixelsY();
521 void NPatchRenderer::InitializeFromBrokenImage()
523 mCroppedImage = RendererFactory::GetBrokenRendererImage();
524 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
526 mStretchPixelsX.Clear();
527 mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
528 mStretchPixelsY.Clear();
529 mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
532 void NPatchRenderer::ApplyImageToSampler()
534 TextureSet textureSet = mImpl->mRenderer.GetTextures();
537 textureSet.SetImage( 0u, mCroppedImage );
539 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
541 //special case for 9 patch
542 Uint16Pair stretchX = mStretchPixelsX[ 0 ];
543 Uint16Pair stretchY = mStretchPixelsY[ 0 ];
545 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
546 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
548 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
549 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
550 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
551 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
555 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
556 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
558 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", mStretchPixelsX, mImageSize.GetWidth() );
559 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", mStretchPixelsY, mImageSize.GetHeight() );
564 Geometry NPatchRenderer::CreateGeometry( Uint16Pair gridSize )
566 uint16_t gridWidth = gridSize.GetWidth();
567 uint16_t gridHeight = gridSize.GetHeight();
570 Vector< Vector2 > vertices;
571 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
573 for( int y = 0; y < gridHeight + 1; ++y )
575 for( int x = 0; x < gridWidth + 1; ++x )
577 AddVertex( vertices, x, y );
582 //TODO: compare performance with triangle strip when Geometry supports it
583 Vector< unsigned short > indices;
584 indices.Reserve( gridWidth * gridHeight * 6 );
586 unsigned int rowIdx = 0;
587 unsigned int nextRowIdx = gridWidth + 1;
588 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
590 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
592 AddQuadIndices( indices, rowIdx, nextRowIdx );
596 return GenerateGeometry( vertices, indices );
599 Geometry NPatchRenderer::CreateGeometryBorder( Uint16Pair gridSize )
601 uint16_t gridWidth = gridSize.GetWidth();
602 uint16_t gridHeight = gridSize.GetHeight();
605 Vector< Vector2 > vertices;
606 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
612 for( int x = 0; x < gridWidth + 1; ++x )
614 AddVertex( vertices, x, y );
618 for(; y < gridHeight - 1; ++y)
621 AddVertex( vertices, 0, y );
622 AddVertex( vertices, 1, y );
625 AddVertex( vertices, gridWidth - 1, y );
626 AddVertex( vertices, gridWidth, y );
630 for(; y < gridHeight + 1; ++y)
632 for( int x = 0; x < gridWidth + 1; ++x )
634 AddVertex( vertices, x, y );
639 //TODO: compare performance with triangle strip when Geometry supports it
640 Vector< unsigned short > indices;
641 indices.Reserve( gridWidth * gridHeight * 6 );
644 unsigned int rowIdx = 0 ;
645 unsigned int nextRowIdx = gridWidth + 1;
646 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
648 AddQuadIndices( indices, rowIdx, nextRowIdx );
653 rowIdx = gridWidth + 1;
654 nextRowIdx = ( gridWidth + 1 ) * 2;
656 unsigned increment = gridWidth - 1;
661 AddQuadIndices( indices, rowIdx, nextRowIdx );
663 rowIdx = gridWidth * 2;
664 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
666 AddQuadIndices( indices, rowIdx, nextRowIdx );
669 rowIdx = nextRowIdx - 2;
670 nextRowIdx = rowIdx + 4;
671 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
673 AddQuadIndices( indices, rowIdx, nextRowIdx );
678 AddQuadIndices( indices, rowIdx, nextRowIdx );
681 nextRowIdx += gridWidth - 1;
683 AddQuadIndices( indices, rowIdx, nextRowIdx );
687 rowIdx = nextRowIdx - gridWidth + 1;
688 nextRowIdx = rowIdx + gridWidth + 1;
689 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
691 AddQuadIndices( indices, rowIdx, nextRowIdx );
694 return GenerateGeometry( vertices, indices );
697 } // namespace Internal
699 } // namespace Toolkit