Merge changes I48753b8f,If7ef493d into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / renderers / npatch / npatch-renderer.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include "npatch-renderer.h"
20
21 // EXTERNAL INCLUDES
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
26 // INTERNAL IINCLUDES
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>
31
32
33 namespace Dali
34 {
35
36 namespace Toolkit
37 {
38
39 namespace Internal
40 {
41
42 namespace
43 {
44 const char * const RENDERER_TYPE("renderer-type");
45 const char * const RENDERER_TYPE_VALUE("n-patch-renderer");
46
47 const char * const IMAGE_URL_NAME("image-url");
48 const char * const BORDER_ONLY("border-only");
49
50 std::string TEXTURE_UNIFORM_NAME = "sTexture";
51
52 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
53     attribute mediump vec2 aPosition;\n
54     varying mediump vec2 vTexCoord;\n
55     uniform mediump mat4 uModelMatrix;\n
56     uniform mediump mat4 uMvpMatrix;\n
57     uniform mediump vec3 uSize;\n
58     uniform mediump vec2 uFixed[ 3 ];\n
59     uniform mediump vec2 uStretchTotal;\n
60     \n
61     void main()\n
62     {\n
63       mediump vec2 scale        = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
64       mediump vec2 size         = uSize.xy * scale;\n
65       \n
66       mediump vec2 fixedFactor  = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y  + 1.0 ) * 0.5 ) ].y );\n
67       mediump vec2 stretch      = floor( aPosition * 0.5 );\n
68       mediump vec2 fixedTotal   = uFixed[ 2 ];\n
69       \n
70       mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
71       vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
72       vertexPosition.xy =  vertexPosition.xy / scale;\n
73       \n
74       vertexPosition = uMvpMatrix * vertexPosition;\n
75       \n
76       vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
77       \n
78       gl_Position = vertexPosition;\n
79     }\n
80 );
81
82 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
83   varying mediump vec2 vTexCoord;\n
84   uniform sampler2D sTexture;\n
85   uniform lowp vec4 uColor;\n
86   \n
87   void main()\n
88   {\n
89     gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
90   }\n
91 );
92
93 /**
94  * @brief Creates the geometry formed from the vertices and indices
95  *
96  * @param[in]  vertices             The vertices to generate the geometry from
97  * @param[in]  indices              The indices to generate the geometry from
98  * @return The geometry formed from the vertices and indices
99  */
100 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned int >& indices )
101 {
102   Property::Map vertexFormat;
103   vertexFormat[ "aPosition" ] = Property::VECTOR2;
104   PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat, vertices.Size() );
105   if( vertices.Size() > 0 )
106   {
107     vertexPropertyBuffer.SetData( &vertices[ 0 ] );
108   }
109
110   Property::Map indexFormat;
111   indexFormat[ "indices" ] = Property::INTEGER;
112   PropertyBuffer indexPropertyBuffer = PropertyBuffer::New( indexFormat, indices.Size() );
113   if( indices.Size() > 0 )
114   {
115     indexPropertyBuffer.SetData( &indices[ 0 ] );
116   }
117
118   // Create the geometry object
119   Geometry geometry = Geometry::New();
120   geometry.AddVertexBuffer( vertexPropertyBuffer );
121   geometry.SetIndexBuffer( indexPropertyBuffer );
122
123   return geometry;
124 }
125
126 /**
127  * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
128  *
129  * @param[out] indices     The indices to add to
130  * @param[in]  rowIdx      The row index to start the quad
131  * @param[in]  nextRowIdx  The index to the next row
132  */
133 void AddQuadIndices( Vector< unsigned int >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
134 {
135   indices.PushBack( rowIdx );
136   indices.PushBack( nextRowIdx + 1 );
137   indices.PushBack( rowIdx + 1 );
138
139   indices.PushBack( rowIdx );
140   indices.PushBack( nextRowIdx );
141   indices.PushBack( nextRowIdx + 1 );
142 }
143
144 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
145 {
146   vertices.PushBack( Vector2( x, y ) );
147 }
148
149 } //unnamed namespace
150
151 /////////////////NPatchRenderer////////////////
152
153 NPatchRenderer::NPatchRenderer( RendererFactoryCache& factoryCache )
154 : ControlRenderer( factoryCache ),
155   mBorderOnly( false )
156 {
157 }
158
159 NPatchRenderer::~NPatchRenderer()
160 {
161 }
162
163 void NPatchRenderer::DoInitialize( const Property::Map& propertyMap )
164 {
165   Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
166   if( imageURLValue )
167   {
168     //Read the border-only property first since InitialiseFromImage relies on mBorderOnly to be properly set
169     Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
170     if( borderOnlyValue )
171     {
172       borderOnlyValue->Get( mBorderOnly );
173     }
174
175     if( imageURLValue->Get( mImageUrl ) )
176     {
177       NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
178       InitialiseFromImage( nPatch );
179     }
180     else
181     {
182       CreateErrorImage();
183       DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
184     }
185   }
186 }
187
188 void NPatchRenderer::GetNaturalSize( Vector2& naturalSize ) const
189 {
190   if( mImage )
191   {
192     naturalSize.x = mImage.GetWidth();
193     naturalSize.y = mImage.GetHeight();
194     return;
195   }
196   else if( !mImageUrl.empty() )
197   {
198     ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
199     naturalSize.x = dimentions.GetWidth();
200     naturalSize.y = dimentions.GetHeight();
201     return;
202   }
203
204   naturalSize = Vector2::ZERO;
205 }
206
207 void NPatchRenderer::SetClipRect( const Rect<int>& clipRect )
208 {
209   ControlRenderer::SetClipRect( clipRect );
210   //ToDo: renderer responds to the clipRect change
211 }
212
213 void NPatchRenderer::SetOffset( const Vector2& offset )
214 {
215   //ToDo: renderer applies the offset
216 }
217
218 void NPatchRenderer::InitializeRenderer( Renderer& renderer )
219 {
220   Geometry geometry;
221   if( !mBorderOnly )
222   {
223     geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY );
224     if( !geometry )
225     {
226       geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
227       mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY, geometry );
228     }
229   }
230   else
231   {
232     geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
233     if( !geometry )
234     {
235       geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
236       mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
237     }
238   }
239
240   Shader shader = mFactoryCache.GetShader( RendererFactoryCache::NINE_PATCH_SHADER );
241   if( !shader )
242   {
243     shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
244     mFactoryCache.SaveShader( RendererFactoryCache::NINE_PATCH_SHADER, shader );
245   }
246
247   if( !renderer )
248   {
249     Material material = Material::New( shader );
250     renderer = Renderer::New( geometry, material );
251   }
252   else
253   {
254     mImpl->mRenderer.SetGeometry( geometry );
255     Material material = mImpl->mRenderer.GetMaterial();
256     if( material )
257     {
258       material.SetShader( shader );
259     }
260   }
261 }
262
263 void NPatchRenderer::DoSetOnStage( Actor& actor )
264 {
265   if( !mCroppedImage )
266   {
267     if( !mImageUrl.empty() )
268     {
269       NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
270       InitialiseFromImage( nPatch );
271     }
272     else if( mImage )
273     {
274       InitialiseFromImage( mImage );
275     }
276   }
277
278   if( mCroppedImage )
279   {
280     ApplyImageToSampler();
281   }
282 }
283
284 void NPatchRenderer::DoSetOffStage( Actor& actor )
285 {
286   mCroppedImage.Reset();
287 }
288
289 void NPatchRenderer::DoCreatePropertyMap( Property::Map& map ) const
290 {
291   map.Clear();
292   map.Insert( RENDERER_TYPE, RENDERER_TYPE_VALUE );
293   if( !mImageUrl.empty() )
294   {
295     map.Insert( IMAGE_URL_NAME, mImageUrl );
296   }
297   else if( mImage )
298   {
299     map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
300   }
301   map.Insert( BORDER_ONLY, mBorderOnly );
302 }
303
304 void NPatchRenderer::SetImage( const std::string& imageUrl, bool borderOnly )
305 {
306   mBorderOnly = borderOnly;
307   mImage.Reset();
308   if( mImageUrl == imageUrl )
309   {
310     return;
311   }
312
313   mImageUrl = imageUrl;
314   NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
315   InitialiseFromImage( nPatch );
316
317   if( mCroppedImage && mImpl->mIsOnStage )
318   {
319     ApplyImageToSampler();
320   }
321 }
322
323 void NPatchRenderer::SetImage( NinePatchImage image, bool borderOnly )
324 {
325   mBorderOnly = borderOnly;
326   mImageUrl.empty();
327   if( mImage == image )
328   {
329     return;
330   }
331
332   mImage = image;
333   InitialiseFromImage( mImage );
334
335   if( mCroppedImage && mImpl->mIsOnStage )
336   {
337     ApplyImageToSampler();
338   }
339 }
340
341 void NPatchRenderer::InitialiseFromImage( NinePatchImage nPatch )
342 {
343   mCroppedImage = nPatch.CreateCroppedBufferImage();
344   if( !mCroppedImage )
345   {
346     DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
347     CreateErrorImage();
348     return;
349   }
350
351   mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
352
353   mStretchPixelsX = nPatch.GetStretchPixelsX();
354   mStretchPixelsY = nPatch.GetStretchPixelsY();
355 }
356
357 void NPatchRenderer::CreateErrorImage()
358 {
359   mImageSize = ImageDimensions( 1, 1 );
360
361   BufferImage bufferImage = BufferImage::New( mImageSize.GetWidth(), mImageSize.GetHeight(), Pixel::RGBA8888 );
362   mCroppedImage = bufferImage;
363   PixelBuffer* pixbuf = bufferImage.GetBuffer();
364
365   for( size_t i = 0; i < mImageSize.GetWidth() * mImageSize.GetHeight() * 4u; )
366   {
367     pixbuf[ i++ ] = 0;
368     pixbuf[ i++ ] = 0;
369     pixbuf[ i++ ] = 0;
370     pixbuf[ i++ ] = 255;
371   }
372
373   mStretchPixelsX.Clear();
374   mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
375   mStretchPixelsY.Clear();
376   mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
377 }
378
379 void NPatchRenderer::ApplyImageToSampler()
380 {
381   Material material = mImpl->mRenderer.GetMaterial();
382   if( material )
383   {
384     Sampler sampler;
385     for( std::size_t i = 0; i < material.GetNumberOfSamplers(); ++i )
386     {
387       sampler = material.GetSamplerAt( i );
388       if( sampler.GetUniformName() == TEXTURE_UNIFORM_NAME )
389       {
390         sampler.SetImage( mCroppedImage );
391         break;
392       }
393     }
394     if( !sampler )
395     {
396       sampler = Sampler::New( mCroppedImage, TEXTURE_UNIFORM_NAME );
397       material.AddSampler( sampler );
398     }
399
400     if( mStretchPixelsX.Size() > 0 && mStretchPixelsY.Size() > 0 )
401     {
402       //only 9 patch supported for now
403       Uint16Pair stretchX = mStretchPixelsX[ 0 ];
404       Uint16Pair stretchY = mStretchPixelsY[ 0 ];
405
406       uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
407       uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
408
409       sampler.RegisterProperty( "uFixed[0]", Vector2::ZERO );
410       sampler.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
411       sampler.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
412       sampler.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
413     }
414   }
415 }
416
417 Geometry NPatchRenderer::CreateGeometry( Uint16Pair gridSize )
418 {
419   uint16_t gridWidth = gridSize.GetWidth();
420   uint16_t gridHeight = gridSize.GetHeight();
421
422   // Create vertices
423   Vector< Vector2 > vertices;
424   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
425
426   for( int y = 0; y < gridHeight + 1; ++y )
427   {
428     for( int x = 0; x < gridWidth + 1; ++x )
429     {
430       AddVertex( vertices, x, y );
431     }
432   }
433
434   // Create indices
435   //TODO: compare performance with triangle strip when Geometry supports it
436   Vector< unsigned int > indices;
437   indices.Reserve( gridWidth * gridHeight * 6 );
438
439   unsigned int rowIdx     = 0;
440   unsigned int nextRowIdx = gridWidth + 1;
441   for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
442   {
443     for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
444     {
445       AddQuadIndices( indices, rowIdx, nextRowIdx );
446     }
447   }
448
449   return GenerateGeometry( vertices, indices );
450 }
451
452 Geometry NPatchRenderer::CreateGeometryBorder( Uint16Pair gridSize )
453 {
454   uint16_t gridWidth = gridSize.GetWidth();
455   uint16_t gridHeight = gridSize.GetHeight();
456
457   // Create vertices
458   Vector< Vector2 > vertices;
459   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
460
461   //top
462   int y = 0;
463   for(; y < 2; ++y)
464   {
465     for( int x = 0; x < gridWidth + 1; ++x )
466     {
467       AddVertex( vertices, x, y );
468     }
469   }
470
471   for(; y < gridHeight - 1; ++y)
472   {
473     //left
474     AddVertex( vertices, 0, y );
475     AddVertex( vertices, 1, y );
476
477     //right
478     AddVertex( vertices, gridWidth - 1, y );
479     AddVertex( vertices, gridWidth, y );
480   }
481
482   //bottom
483   for(; y < gridHeight + 1; ++y)
484   {
485     for( int x = 0; x < gridWidth + 1; ++x )
486     {
487       AddVertex( vertices, x, y );
488     }
489   }
490
491   // Create indices
492   //TODO: compare performance with triangle strip when Geometry supports it
493   Vector< unsigned int > indices;
494   indices.Reserve( gridWidth * gridHeight * 6 );
495
496   //top
497   unsigned int rowIdx     = 0 ;
498   unsigned int nextRowIdx = gridWidth + 1;
499   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
500   {
501     AddQuadIndices( indices, rowIdx, nextRowIdx );
502   }
503
504   if(gridHeight > 2)
505   {
506     rowIdx     = gridWidth + 1;
507     nextRowIdx = ( gridWidth + 1 ) * 2;
508
509     unsigned increment = gridWidth - 1;
510     if(gridHeight > 3)
511     {
512       increment = 2;
513       //second row left
514       AddQuadIndices( indices, rowIdx, nextRowIdx );
515
516       rowIdx     = gridWidth * 2;
517       nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
518       //second row right
519       AddQuadIndices( indices, rowIdx, nextRowIdx );
520
521       //left and right
522       rowIdx     = nextRowIdx - 2;
523       nextRowIdx = rowIdx + 4;
524       for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
525       {
526         AddQuadIndices( indices, rowIdx, nextRowIdx );
527       }
528     }
529
530     //second row left
531     AddQuadIndices( indices, rowIdx, nextRowIdx );
532
533     rowIdx     += increment;
534     nextRowIdx += gridWidth - 1;
535     //second row right
536     AddQuadIndices( indices, rowIdx, nextRowIdx );
537   }
538
539   //bottom
540   rowIdx     = nextRowIdx - gridWidth + 1;
541   nextRowIdx = rowIdx + gridWidth + 1;
542   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
543   {
544     AddQuadIndices( indices, rowIdx, nextRowIdx );
545   }
546
547   return GenerateGeometry( vertices, indices );
548 }
549
550 } // namespace Internal
551
552 } // namespace Toolkit
553
554 } // namespace Dali