2 * Copyright (c) 2020 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/devel-api/rendering/renderer-devel.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/integration-api/debug.h>
27 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
28 #include <dali-toolkit/public-api/visuals/visual-properties.h>
29 #include <dali-toolkit/internal/visuals/npatch-loader.h>
30 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
31 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
32 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
33 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
34 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
35 #include <dali-toolkit/internal/visuals/rendering-addon.h>
48 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
49 attribute mediump vec2 aPosition;\n
50 varying mediump vec2 vTexCoord;\n
51 varying mediump vec2 vMaskTexCoord;\n
52 uniform highp mat4 uMvpMatrix;\n
53 uniform highp vec3 uSize;\n
54 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
55 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
58 // Visual size and offset
59 uniform mediump vec2 offset;\n
60 uniform highp vec2 size;\n
61 uniform mediump vec4 offsetSizeMode;\n
62 uniform mediump vec2 origin;\n
63 uniform mediump vec2 anchorPoint;\n
64 uniform mediump vec2 extraSize;\n
68 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
69 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
71 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
72 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
74 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
75 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
77 mediump vec4 gridPosition = vec4( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal, 0.0, 1.0 );\n
78 mediump vec4 vertexPosition = gridPosition;\n
79 vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
80 vertexPosition.xy += anchorPoint*visualSize + (visualOffset + origin)*uSize.xy;\n
81 vertexPosition = uMvpMatrix * vertexPosition;\n
83 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
84 vMaskTexCoord = gridPosition.xy / visualSize;\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 varying mediump vec2 vMaskTexCoord;\n
94 uniform highp mat4 uMvpMatrix;\n
95 uniform highp vec3 uSize;\n
96 uniform mediump vec2 uFixed[ 3 ];\n
97 uniform mediump vec2 uStretchTotal;\n
99 //Visual size and offset
100 uniform mediump vec2 offset;\n
101 uniform highp vec2 size;\n
102 uniform mediump vec4 offsetSizeMode;\n
103 uniform mediump vec2 origin;\n
104 uniform mediump vec2 anchorPoint;\n
105 uniform mediump vec2 extraSize;\n
109 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
110 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
112 mediump vec2 size = visualSize.xy;\n
114 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
115 mediump vec2 stretch = floor( aPosition * 0.5 );\n
116 mediump vec2 fixedTotal = uFixed[ 2 ];\n
118 mediump vec4 gridPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
119 mediump vec4 vertexPosition = gridPosition;\n
120 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
121 vertexPosition.xy += anchorPoint*size + (visualOffset + origin)*uSize.xy;\n
123 vertexPosition = uMvpMatrix * vertexPosition;\n
125 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
127 vMaskTexCoord = gridPosition.xy / size;\n
128 gl_Position = vertexPosition;\n
132 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
133 varying mediump vec2 vTexCoord;\n
134 uniform sampler2D sTexture;\n
135 uniform lowp vec4 uColor;\n
136 uniform lowp vec3 mixColor;\n
137 uniform lowp float preMultipliedAlpha;\n
141 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * vec4( mixColor, 1.0 );\n
145 const char* FRAGMENT_MASK_SHADER = DALI_COMPOSE_SHADER(
146 varying mediump vec2 vTexCoord;\n
147 varying mediump vec2 vMaskTexCoord;\n
148 uniform sampler2D sTexture;\n
149 uniform sampler2D sMask;\n
150 uniform lowp vec4 uColor;\n
151 uniform lowp vec3 mixColor;\n
152 uniform lowp float preMultipliedAlpha;\n
153 uniform mediump float auxiliaryImageAlpha;\n
157 // Where mask image is transparent, all of background image must show through.
158 // where mask image is opaque, only mask should be shown
159 // where mask is translucent, less of background should be shown.
160 // auxiliaryImageAlpha controls how much of mask is visible
162 mediump vec4 color = texture2D( sTexture, vTexCoord );\n
163 mediump vec4 mask = texture2D( sMask, vMaskTexCoord );\n
165 mediump vec3 mixedColor = color.rgb * mix( 1.0-mask.a, 1.0, 1.0-auxiliaryImageAlpha)
166 + mask.rgb*mask.a * auxiliaryImageAlpha;\n
167 gl_FragColor = vec4(mixedColor,1.0) * uColor * vec4( mixColor, 1.0 );\n
172 * @brief Creates the geometry formed from the vertices and indices
174 * @param[in] vertices The vertices to generate the geometry from
175 * @param[in] indices The indices to generate the geometry from
176 * @return The geometry formed from the vertices and indices
178 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
180 Property::Map vertexFormat;
181 vertexFormat[ "aPosition" ] = Property::VECTOR2;
182 VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
183 if( vertices.Size() > 0 )
185 vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
188 // Create the geometry object
189 Geometry geometry = Geometry::New();
190 geometry.AddVertexBuffer( vertexBuffer );
191 if( indices.Size() > 0 )
193 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
201 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
203 * @param[out] indices The indices to add to
204 * @param[in] rowIdx The row index to start the quad
205 * @param[in] nextRowIdx The index to the next row
207 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
209 indices.PushBack( rowIdx );
210 indices.PushBack( nextRowIdx + 1 );
211 indices.PushBack( rowIdx + 1 );
213 indices.PushBack( rowIdx );
214 indices.PushBack( nextRowIdx );
215 indices.PushBack( nextRowIdx + 1 );
218 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
220 vertices.PushBack( Vector2( x, y ) );
223 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent)
225 uint16_t prevEnd = 0;
226 uint16_t prevFix = 0;
227 uint16_t prevStretch = 0;
229 for( NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
231 uint16_t start = it->GetX();
232 uint16_t end = it->GetY();
234 uint16_t fix = prevFix + start - prevEnd;
235 uint16_t stretch = prevStretch + end - start;
237 std::stringstream uniform;
238 uniform << uniformName << "[" << i << "]";
239 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
243 prevStretch = stretch;
247 prevFix += imageExtent - prevEnd;
248 std::stringstream uniform;
249 uniform << uniformName << "[" << i << "]";
250 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
254 } //unnamed namespace
256 /////////////////NPatchVisual////////////////
258 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl, const Property::Map& properties )
260 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
261 nPatchVisual->mImageUrl = imageUrl;
262 nPatchVisual->SetProperties( properties );
267 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl )
269 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
270 nPatchVisual->mImageUrl = imageUrl;
275 void NPatchVisual::LoadImages()
277 TextureManager& textureManager = mFactoryCache.GetTextureManager();
278 bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
280 if( mId == NPatchData::INVALID_NPATCH_DATA_ID && mImageUrl.IsLocalResource() )
282 bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
283 mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
285 const NPatchData* data;
286 if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
288 EnablePreMultipliedAlpha( data->IsPreMultiplied() );
292 if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
294 // Load the auxiliary image
295 auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
296 mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
297 SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
298 this, true, preMultiplyOnLoading );
302 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
307 // load now if not already loaded
308 const NPatchData* data;
309 if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() != NPatchData::LoadingState::LOADING )
311 naturalSize.x = data->GetCroppedWidth();
312 naturalSize.y = data->GetCroppedHeight();
316 if( mImageUrl.IsValid() )
318 ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
319 if( dimensions != ImageDimensions( 0, 0 ) )
321 naturalSize.x = dimensions.GetWidth();
322 naturalSize.y = dimensions.GetHeight();
327 if( mAuxiliaryPixelBuffer )
329 naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) );
330 naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) );
334 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
336 // URL is already passed in via constructor
338 Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
339 if( borderOnlyValue )
341 borderOnlyValue->Get( mBorderOnly );
344 Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER );
345 if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
347 // Not a rect so try vector4
349 if( borderValue->Get( border ) )
351 mBorder.left = static_cast< int >( border.x );
352 mBorder.right = static_cast< int >( border.y );
353 mBorder.bottom = static_cast< int >( border.z );
354 mBorder.top = static_cast< int >( border.w );
358 Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME );
362 if( auxImage->Get( url ) )
368 Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME );
371 auxImageAlpha->Get( mAuxiliaryImageAlpha );
374 Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
375 if( synchronousLoading )
378 synchronousLoading->Get( sync );
381 mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
385 mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
389 Property::Value* releasePolicy = propertyMap.Find( Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME );
392 releasePolicy->Get( mReleasePolicy );
396 void NPatchVisual::DoSetOnScene( Actor& actor )
398 // load when first go on stage
401 const NPatchData* data;
402 if( mLoader.GetNPatchData( mId, data ) )
404 Geometry geometry = CreateGeometry();
405 Shader shader = CreateShader();
407 mImpl->mRenderer = Renderer::New( geometry, shader );
409 mPlacementActor = actor;
410 if( data->GetLoadingState() != NPatchData::LoadingState::LOADING )
412 if( RenderingAddOn::Get().IsValid() )
414 RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->GetRenderingMap() );
417 ApplyTextureAndUniforms();
418 actor.AddRenderer( mImpl->mRenderer );
419 mPlacementActor.Reset();
421 // npatch loaded and ready to display
422 ResourceReady( Toolkit::Visual::ResourceStatus::READY );
427 void NPatchVisual::DoSetOffScene( Actor& actor )
429 if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED)
431 mLoader.Remove(mId, this);
432 mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
433 mId = NPatchData::INVALID_NPATCH_DATA_ID;
436 actor.RemoveRenderer( mImpl->mRenderer );
437 mImpl->mRenderer.Reset();
438 mPlacementActor.Reset();
441 void NPatchVisual::OnSetTransform()
443 if( mImpl->mRenderer )
445 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
449 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
452 bool sync = IsSynchronousLoadingRequired();
453 map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
454 map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
455 map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
456 map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
457 map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder );
458 map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
460 if( mAuxiliaryUrl.IsValid() )
462 map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
463 map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
467 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
469 if( mAuxiliaryUrl.IsValid() )
471 map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
472 map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
476 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
477 : Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH ),
479 mLoader( factoryCache.GetNPatchLoader() ),
482 mId(NPatchData::INVALID_NPATCH_DATA_ID),
483 mBorderOnly( false ),
485 mAuxiliaryImageAlpha( 0.0f ),
486 mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DETACHED )
488 EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
491 NPatchVisual::~NPatchVisual()
493 if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ))
495 mLoader.Remove(mId, this);
496 mId = NPatchData::INVALID_NPATCH_DATA_ID;
500 Geometry NPatchVisual::CreateGeometry()
503 const NPatchData* data;
504 if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
506 if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 )
508 if( DALI_UNLIKELY( mBorderOnly ) )
510 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
514 if( data->GetRenderingMap() )
516 uint32_t elementCount[2];
517 geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount );
518 if( mImpl->mRenderer )
520 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
525 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
529 else if( data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0)
531 Uint16Pair gridSize( 2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1 );
532 if( !data->GetRenderingMap() )
534 geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
538 uint32_t elementCount[2];
539 geometry = !mBorderOnly ?
540 RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount ) : CreateBorderGeometry(gridSize );
541 if( mImpl->mRenderer )
543 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
550 // no N patch data so use default geometry
551 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
556 Shader NPatchVisual::CreateShader()
559 const NPatchData* data;
560 // 0 is either no data (load failed?) or no stretch regions on image
561 // for both cases we use the default shader
562 NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
563 NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
565 auto fragmentShader = mAuxiliaryPixelBuffer ? FRAGMENT_MASK_SHADER
567 auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
568 : VisualFactoryCache::NINE_PATCH_SHADER;
570 // ask loader for the regions
571 if( mLoader.GetNPatchData( mId, data ) )
573 xStretchCount = data->GetStretchPixelsX().Count();
574 yStretchCount = data->GetStretchPixelsY().Count();
577 if( DALI_LIKELY( !mImpl->mCustomShader ) )
579 if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
580 ( xStretchCount == 0 && yStretchCount == 0 ) ) )
582 shader = mFactoryCache.GetShader( shaderType );
583 if( DALI_UNLIKELY( !shader ) )
585 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader );
586 // Only cache vanilla 9 patch shaders
587 mFactoryCache.SaveShader( shaderType, shader );
590 else if( xStretchCount > 0 || yStretchCount > 0)
592 std::stringstream vertexShader;
593 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
594 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
597 shader = Shader::New( vertexShader.str(), fragmentShader );
602 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
604 if( !mImpl->mCustomShader->mFragmentShader.empty() )
606 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
608 hints = mImpl->mCustomShader->mHints;
610 /* Apply Custom Vertex Shader only if image is 9-patch */
611 if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
612 ( xStretchCount == 0 && yStretchCount == 0 ) )
614 const char* vertexShader = VERTEX_SHADER_3X3;
616 if( !mImpl->mCustomShader->mVertexShader.empty() )
618 vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
620 shader = Shader::New( vertexShader, fragmentShader, hints );
622 else if( xStretchCount > 0 || yStretchCount > 0)
624 std::stringstream vertexShader;
625 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
626 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
629 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
636 void NPatchVisual::ApplyTextureAndUniforms()
638 const NPatchData* data;
639 TextureSet textureSet;
641 if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
643 textureSet = data->GetTextures();
645 if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 )
647 //special case for 9 patch
648 Uint16Pair stretchX = data->GetStretchPixelsX()[ 0 ];
649 Uint16Pair stretchY = data->GetStretchPixelsY()[ 0 ];
651 uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0;
652 uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0;
654 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
655 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
656 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->GetCroppedWidth() - stretchWidth, data->GetCroppedHeight() - stretchHeight ) );
657 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
661 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
662 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
664 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->GetStretchPixelsX(), data->GetCroppedWidth() );
665 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->GetStretchPixelsY(), data->GetCroppedHeight() );
670 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
671 textureSet = TextureSet::New();
673 Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
674 textureSet.SetTexture( 0u, croppedImage );
675 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
676 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
677 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
678 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
681 if( mAuxiliaryPixelBuffer )
683 // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
684 // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
685 // on GL interpolation alone.
686 if( mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() &&
687 mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight() )
689 mAuxiliaryPixelBuffer.Resize( data->GetCroppedWidth(), data->GetCroppedHeight() );
692 // Note, this resets mAuxiliaryPixelBuffer handle
693 auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer );
695 auto texture = Texture::New( TextureType::TEXTURE_2D,
696 auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(),
697 auxiliaryPixelData.GetHeight() );
698 texture.Upload( auxiliaryPixelData );
699 textureSet.SetTexture( 1, texture );
700 mImpl->mRenderer.RegisterProperty( DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
701 AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
703 mImpl->mRenderer.SetTextures( textureSet );
705 // Register transform properties
706 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
709 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
711 Geometry geometry = mFactoryCache.GetGeometry( subType );
714 if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
716 geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
718 else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
720 geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
722 mFactoryCache.SaveGeometry( subType, geometry );
727 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
729 uint16_t gridWidth = gridSize.GetWidth();
730 uint16_t gridHeight = gridSize.GetHeight();
733 Vector< Vector2 > vertices;
734 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
736 for( int y = 0; y < gridHeight + 1; ++y )
738 for( int x = 0; x < gridWidth + 1; ++x )
740 AddVertex( vertices, x, y );
745 Vector< unsigned short > indices;
746 indices.Reserve( gridWidth * gridHeight * 6 );
748 unsigned int rowIdx = 0;
749 unsigned int nextRowIdx = gridWidth + 1;
750 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
752 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
754 AddQuadIndices( indices, rowIdx, nextRowIdx );
758 return GenerateGeometry( vertices, indices );
761 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
763 uint16_t gridWidth = gridSize.GetWidth();
764 uint16_t gridHeight = gridSize.GetHeight();
767 Vector< Vector2 > vertices;
768 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
774 for( int x = 0; x < gridWidth + 1; ++x )
776 AddVertex( vertices, x, y );
780 for(; y < gridHeight - 1; ++y)
783 AddVertex( vertices, 0, y );
784 AddVertex( vertices, 1, y );
787 AddVertex( vertices, gridWidth - 1, y );
788 AddVertex( vertices, gridWidth, y );
792 for(; y < gridHeight + 1; ++y)
794 for( int x = 0; x < gridWidth + 1; ++x )
796 AddVertex( vertices, x, y );
801 Vector< unsigned short > indices;
802 indices.Reserve( gridWidth * gridHeight * 6 );
805 unsigned int rowIdx = 0 ;
806 unsigned int nextRowIdx = gridWidth + 1;
807 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
809 AddQuadIndices( indices, rowIdx, nextRowIdx );
814 rowIdx = gridWidth + 1;
815 nextRowIdx = ( gridWidth + 1 ) * 2;
817 unsigned increment = gridWidth - 1;
822 AddQuadIndices( indices, rowIdx, nextRowIdx );
824 rowIdx = gridWidth * 2;
825 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
827 AddQuadIndices( indices, rowIdx, nextRowIdx );
830 rowIdx = nextRowIdx - 2;
831 nextRowIdx = rowIdx + 4;
832 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
834 AddQuadIndices( indices, rowIdx, nextRowIdx );
839 AddQuadIndices( indices, rowIdx, nextRowIdx );
842 nextRowIdx += gridWidth - 1;
844 AddQuadIndices( indices, rowIdx, nextRowIdx );
848 rowIdx = nextRowIdx - gridWidth + 1;
849 nextRowIdx = rowIdx + gridWidth + 1;
850 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
852 AddQuadIndices( indices, rowIdx, nextRowIdx );
855 return GenerateGeometry( vertices, indices );
858 void NPatchVisual::SetResource()
860 const NPatchData* data;
861 if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
863 Geometry geometry = CreateGeometry();
864 Shader shader = CreateShader();
866 mImpl->mRenderer.SetGeometry( geometry );
867 mImpl->mRenderer.SetShader( shader );
869 Actor actor = mPlacementActor.GetHandle();
872 ApplyTextureAndUniforms();
873 actor.AddRenderer( mImpl->mRenderer );
874 mPlacementActor.Reset();
876 // npatch loaded and ready to display
877 ResourceReady( Toolkit::Visual::ResourceStatus::READY );
882 void NPatchVisual::UploadComplete( bool loadSuccess, int32_t textureId, TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, bool preMultiplied )
884 EnablePreMultipliedAlpha( preMultiplied );
887 // Image loaded and ready to display
888 ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
891 if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
897 void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
899 if( loadSuccess && url.GetUrl() == mAuxiliaryUrl.GetUrl() )
901 mAuxiliaryPixelBuffer = pixelBuffer;
906 // Image loaded and ready to display
907 ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
911 } // namespace Internal
913 } // namespace Toolkit