[3.0] Text - Fix for emojis resampling.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / rendering / atlas / text-atlas-renderer.cpp
1 /*
2  * Copyright (c) 2016 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 <dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/rendering/geometry.h>
23 #include <dali/public-api/rendering/renderer.h>
24 #include <dali/devel-api/text-abstraction/font-client.h>
25 #include <dali/integration-api/debug.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
29 #include <dali-toolkit/internal/text/glyph-run.h>
30 #include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
31 #include <dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.h>
32 #include <dali-toolkit/internal/text/text-view.h>
33
34 using namespace Dali;
35 using namespace Dali::Toolkit;
36 using namespace Dali::Toolkit::Text;
37
38 namespace
39 {
40 #if defined(DEBUG_ENABLED)
41   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING");
42 #endif
43
44 #define MAKE_SHADER(A)#A
45
46 const char* VERTEX_SHADER = MAKE_SHADER(
47 attribute mediump vec2    aPosition;
48 attribute mediump vec2    aTexCoord;
49 attribute mediump vec4    aColor;
50 uniform   mediump vec2    uOffset;
51 uniform   mediump mat4    uMvpMatrix;
52 varying   mediump vec2    vTexCoord;
53 varying   mediump vec4    vColor;
54
55 void main()
56 {
57   mediump vec4 position = vec4( aPosition.xy + uOffset, 0.0, 1.0 );
58   gl_Position = uMvpMatrix * position;
59   vTexCoord = aTexCoord;
60   vColor = aColor;
61 }
62 );
63
64 const char* FRAGMENT_SHADER_L8 = MAKE_SHADER(
65 uniform lowp    vec4      uColor;
66 uniform         sampler2D sTexture;
67 varying mediump vec2      vTexCoord;
68 varying mediump vec4      vColor;
69
70 void main()
71 {
72   mediump vec4 color = texture2D( sTexture, vTexCoord );
73   gl_FragColor = vec4( vColor.rgb * uColor.rgb, vColor.a * uColor.a * color.r );
74 }
75 );
76
77 const char* FRAGMENT_SHADER_RGBA = MAKE_SHADER(
78 uniform lowp    vec4      uColor;
79 uniform         sampler2D sTexture;
80 varying mediump vec2      vTexCoord;
81
82 void main()
83 {
84   gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;
85 }
86 );
87
88 const float ZERO( 0.0f );
89 const float HALF( 0.5f );
90 const float ONE( 1.0f );
91 const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
92 const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
93 }
94
95 struct AtlasRenderer::Impl
96 {
97   enum Style
98   {
99     STYLE_NORMAL,
100     STYLE_DROP_SHADOW
101   };
102
103   struct MeshRecord
104   {
105     MeshRecord()
106     : mAtlasId( 0u )
107     {
108     }
109
110     uint32_t mAtlasId;
111     AtlasManager::Mesh2D mMesh;
112     FrameBufferImage mBuffer;
113   };
114
115   /**
116    * brief Struct used to generate the underline mesh.
117    * There is one Extent per line of text.
118    */
119   struct Extent
120   {
121     Extent()
122     : mBaseLine( 0.0f ),
123       mLeft( 0.0f ),
124       mRight( 0.0f ),
125       mUnderlinePosition( 0.0f ),
126       mUnderlineThickness( 0.0f ),
127       mMeshRecordIndex( 0u )
128     {
129     }
130
131     float mBaseLine;
132     float mLeft;
133     float mRight;
134     float mUnderlinePosition;
135     float mUnderlineThickness;
136     uint32_t mMeshRecordIndex;
137   };
138
139   struct MaxBlockSize
140   {
141     MaxBlockSize()
142     : mFontId( 0 ),
143       mNeededBlockWidth( 0 ),
144       mNeededBlockHeight( 0 )
145     {
146     }
147
148     FontId mFontId;
149     uint32_t mNeededBlockWidth;
150     uint32_t mNeededBlockHeight;
151   };
152
153   struct CheckEntry
154   {
155     CheckEntry()
156     : mFontId( 0 ),
157       mIndex( 0 )
158     {
159     }
160
161     FontId mFontId;
162     Text::GlyphIndex mIndex;
163   };
164
165   struct TextCacheEntry
166   {
167     TextCacheEntry()
168     : mFontId( 0 ),
169       mIndex( 0 ),
170       mImageId( 0 )
171     {
172     }
173
174     FontId mFontId;
175     Text::GlyphIndex mIndex;
176     uint32_t mImageId;
177   };
178
179   Impl()
180   : mDepth( 0 )
181   {
182     mGlyphManager = AtlasGlyphManager::Get();
183     mFontClient = TextAbstraction::FontClient::Get();
184
185     mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
186     mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
187     mQuadVertexFormat[ "aColor" ] = Property::VECTOR4;
188   }
189
190   bool IsGlyphUnderlined( GlyphIndex index,
191                           const Vector<GlyphRun>& underlineRuns )
192   {
193     for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
194            endIt = underlineRuns.End();
195            it != endIt;
196          ++it )
197     {
198       const GlyphRun& run = *it;
199
200       if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
201       {
202         return true;
203       }
204     }
205
206     return false;
207   }
208
209   void AddGlyphs( Text::ViewInterface& view,
210                   const Vector<Vector2>& positions,
211                   const Vector<GlyphInfo>& glyphs,
212                   const Vector4& defaultColor,
213                   const Vector4* const colorsBuffer,
214                   const ColorIndex* const colorIndicesBuffer,
215                   int depth,
216                   float minLineOffset )
217   {
218     AtlasManager::AtlasSlot slot;
219     std::vector< MeshRecord > meshContainer;
220     Vector< Extent > extents;
221     TextCacheEntry textCacheEntry;
222     mDepth = depth;
223
224     const Vector2& textSize( view.GetLayoutSize() );
225     const Vector2 halfTextSize( textSize * 0.5f );
226     const Vector2& shadowOffset( view.GetShadowOffset() );
227     const Vector4& shadowColor( view.GetShadowColor() );
228     const bool underlineEnabled( view.IsUnderlineEnabled() );
229     const Vector4& underlineColor( view.GetUnderlineColor() );
230     const float underlineHeight( view.GetUnderlineHeight() );
231
232     const bool useDefaultColor = ( NULL == colorsBuffer );
233
234     // Get the underline runs.
235     const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
236     Vector<GlyphRun> underlineRuns;
237     underlineRuns.Resize( numberOfUnderlineRuns );
238     view.GetUnderlineRuns( underlineRuns.Begin(),
239                            0u,
240                            numberOfUnderlineRuns );
241
242     bool thereAreUnderlinedGlyphs = false;
243
244     float currentUnderlinePosition = ZERO;
245     float currentUnderlineThickness = underlineHeight;
246     uint32_t currentBlockSize = 0;
247     FontId lastFontId = 0;
248     FontId lastUnderlinedFontId = 0;
249     Style style = STYLE_NORMAL;
250
251     if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
252     {
253       style = STYLE_DROP_SHADOW;
254     }
255
256     CalculateBlocksSize( glyphs );
257
258     // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
259     Vector< TextCacheEntry > newTextCache;
260     const GlyphInfo* const glyphsBuffer = glyphs.Begin();
261     const Vector2* const positionsBuffer = positions.Begin();
262     const Vector2 lineOffsetPosition( minLineOffset, 0.f );
263
264     for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
265     {
266       const GlyphInfo& glyph = *( glyphsBuffer + i );
267       const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
268       thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
269
270       // No operation for white space
271       if( glyph.width && glyph.height )
272       {
273         // Are we still using the same fontId as previous
274         if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
275         {
276           // We need to fetch fresh font underline metrics
277           FontMetrics fontMetrics;
278           mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
279           currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
280           const float descender = ceil( fabsf( fontMetrics.descender ) );
281
282           if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
283           {
284             currentUnderlineThickness = fontMetrics.underlineThickness;
285
286             // Ensure underline will be at least a pixel high
287             if ( currentUnderlineThickness < ONE )
288             {
289               currentUnderlineThickness = ONE;
290             }
291             else
292             {
293               currentUnderlineThickness = ceil( currentUnderlineThickness );
294             }
295           }
296
297           // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
298           if( currentUnderlinePosition > descender )
299           {
300             currentUnderlinePosition = descender;
301           }
302
303           if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
304           {
305             // Move offset down by one ( EFL behavior )
306             currentUnderlinePosition = ONE;
307           }
308
309           lastUnderlinedFontId = glyph.fontId;
310         } // underline
311
312         if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
313         {
314           // Select correct size for new atlas if needed....?
315           if( lastFontId != glyph.fontId )
316           {
317             uint32_t index = 0u;
318             for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
319                    endIt = mBlockSizes.end();
320                  it != endIt;
321                  ++it, ++index )
322             {
323               const MaxBlockSize& blockSize = *it;
324               if( blockSize.mFontId == glyph.fontId )
325               {
326                 currentBlockSize = index;
327                 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
328                                                DEFAULT_ATLAS_HEIGHT,
329                                                blockSize.mNeededBlockWidth,
330                                                blockSize.mNeededBlockHeight );
331               }
332             }
333           }
334
335           // Create a new image for the glyph
336           PixelData bitmap;
337
338           // Whether the current glyph is a color one.
339           const bool isColorGlyph = mFontClient.IsColorGlyph( glyph.fontId, glyph.index );
340
341           // Retrieve the emoji's bitmap.
342           TextAbstraction::FontClient::GlyphBufferData glyphBufferData;
343           glyphBufferData.width = isColorGlyph ? glyph.width : 0;   // Desired width and height.
344           glyphBufferData.height = isColorGlyph ? glyph.height : 0;
345
346           mFontClient.CreateBitmap( glyph.fontId,
347                                     glyph.index,
348                                     glyphBufferData );
349
350           // Create the pixel data.
351           bitmap = PixelData::New( glyphBufferData.buffer,
352                                    glyph.width * glyph.height * GetBytesPerPixel( glyphBufferData.format ),
353                                    glyph.width,
354                                    glyph.height,
355                                    glyphBufferData.format,
356                                    PixelData::DELETE_ARRAY );
357
358           if( bitmap )
359           {
360             MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
361
362             // Ensure that the next image will fit into the current block size
363             bool setSize = false;
364             if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
365             {
366               setSize = true;
367               blockSize.mNeededBlockWidth = bitmap.GetWidth();
368             }
369             if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
370             {
371               setSize = true;
372               blockSize.mNeededBlockHeight = bitmap.GetHeight();
373             }
374
375             if( setSize )
376             {
377               mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
378                                              DEFAULT_ATLAS_HEIGHT,
379                                              blockSize.mNeededBlockWidth,
380                                              blockSize.mNeededBlockHeight );
381             }
382
383             // Locate a new slot for our glyph
384             mGlyphManager.Add( glyph, bitmap, slot );
385           }
386         }
387         else
388         {
389           // We have 2+ copies of the same glyph
390           mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
391         }
392
393         // Move the origin (0,0) of the mesh to the center of the actor
394         const Vector2 position = *( positionsBuffer + i ) - halfTextSize - lineOffsetPosition;
395
396         // Generate mesh data for this quad, plugging in our supplied position
397         AtlasManager::Mesh2D newMesh;
398         mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
399         textCacheEntry.mFontId = glyph.fontId;
400         textCacheEntry.mImageId = slot.mImageId;
401         textCacheEntry.mIndex = glyph.index;
402         newTextCache.PushBack( textCacheEntry );
403
404         AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
405
406         // Get the color of the character.
407         const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i );
408         const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u );
409
410         for( unsigned int index = 0u, size = newMesh.mVertices.Count();
411              index < size;
412              ++index )
413         {
414           AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
415
416           // Set the color of the vertex.
417           vertex.mColor = color;
418         }
419
420         // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
421         StitchTextMesh( meshContainer,
422                         newMesh,
423                         extents,
424                         position.y + glyph.yBearing,
425                         underlineGlyph,
426                         currentUnderlinePosition,
427                         currentUnderlineThickness,
428                         slot );
429         lastFontId = glyph.fontId;
430       }
431     } // glyphs
432
433     // Now remove references for the old text
434     RemoveText();
435     mTextCache.Swap( newTextCache );
436
437     if( thereAreUnderlinedGlyphs )
438     {
439       // Check to see if any of the text needs an underline
440       GenerateUnderlines( meshContainer, extents, underlineColor );
441     }
442
443     // For each MeshData object, create a mesh actor and add to the renderable actor
444     if( !meshContainer.empty() )
445     {
446       if( !mActor )
447       {
448         // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
449         mActor = Actor::New();
450         mActor.SetParentOrigin( ParentOrigin::TOP_LEFT );
451         mActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
452         mActor.SetSize( textSize );
453       }
454
455       for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
456               endIt = meshContainer.end();
457             it != endIt; ++it )
458       {
459         MeshRecord& meshRecord = *it;
460
461         Actor actor = CreateMeshActor( meshRecord, textSize, STYLE_NORMAL );
462
463         // Whether the actor has renderers.
464         const bool hasRenderer = actor.GetRendererCount() > 0u;
465
466         // Create an effect if necessary
467         if( hasRenderer &&
468             ( style == STYLE_DROP_SHADOW ) )
469         {
470           // Change the color of the vertices.
471           for( Vector<AtlasManager::Vertex2D>::Iterator vIt =  meshRecord.mMesh.mVertices.Begin(),
472                  vEndIt = meshRecord.mMesh.mVertices.End();
473                vIt != vEndIt;
474                ++vIt )
475           {
476             AtlasManager::Vertex2D& vertex = *vIt;
477
478             vertex.mColor = shadowColor;
479           }
480
481           Actor shadowActor = CreateMeshActor( meshRecord, textSize, STYLE_DROP_SHADOW );
482 #if defined(DEBUG_ENABLED)
483           shadowActor.SetName( "Text Shadow renderable actor" );
484 #endif
485           // Offset shadow in x and y
486           shadowActor.RegisterProperty("uOffset", shadowOffset );
487           Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
488           int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
489           renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
490           mActor.Add( shadowActor );
491         }
492
493         if( hasRenderer )
494         {
495           mActor.Add( actor );
496         }
497       }
498     }
499 #if defined(DEBUG_ENABLED)
500     Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
501     DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
502                                                 metrics.mGlyphCount,
503                                                 metrics.mAtlasMetrics.mAtlasCount,
504                                                 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
505
506     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
507
508     for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
509     {
510       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "   Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
511                                                  i + 1, i > 8 ? "" : " ",
512                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8  " : "BGRA",
513                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
514                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
515                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
516                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
517                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
518                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
519     }
520 #endif
521   }
522
523   void RemoveText()
524   {
525     for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
526     {
527       mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
528     }
529     mTextCache.Resize( 0 );
530   }
531
532   Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize, Style style )
533   {
534     PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat );
535     quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
536
537     Geometry quadGeometry = Geometry::New();
538     quadGeometry.AddVertexBuffer( quadVertices );
539     quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0],  meshRecord.mMesh.mIndices.Size() );
540
541     TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
542
543     // Choose the shader to use.
544     const bool isColorShader = ( STYLE_DROP_SHADOW != style ) && ( Pixel::BGRA8888 == mGlyphManager.GetPixelFormat( meshRecord.mAtlasId ) );
545     Shader shader;
546     if( isColorShader )
547     {
548       // The glyph is an emoji and is not a shadow.
549       if( !mShaderRgba )
550       {
551         mShaderRgba = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_RGBA );
552       }
553       shader = mShaderRgba;
554     }
555     else
556     {
557       // The glyph is text or a shadow.
558       if( !mShaderL8 )
559       {
560         mShaderL8 = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_L8 );
561       }
562       shader = mShaderL8;
563     }
564
565     Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
566     renderer.SetTextures( textureSet );
567     renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON );
568     renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
569     Actor actor = Actor::New();
570 #if defined(DEBUG_ENABLED)
571     actor.SetName( "Text renderable actor" );
572 #endif
573     actor.AddRenderer( renderer );
574
575     // Keep all of the origins aligned
576     actor.SetParentOrigin( ParentOrigin::TOP_LEFT );
577     actor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
578     actor.SetSize( actorSize );
579     actor.RegisterProperty("uOffset", Vector2::ZERO );
580     return actor;
581   }
582
583   void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
584                        AtlasManager::Mesh2D& newMesh,
585                        Vector< Extent >& extents,
586                        float baseLine,
587                        bool underlineGlyph,
588                        float underlinePosition,
589                        float underlineThickness,
590                        AtlasManager::AtlasSlot& slot )
591   {
592     if ( slot.mImageId )
593     {
594       float left = newMesh.mVertices[ 0 ].mPosition.x;
595       float right = newMesh.mVertices[ 1 ].mPosition.x;
596
597       // Check to see if there's a mesh data object that references the same atlas ?
598       uint32_t index = 0;
599       for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
600               mEndIt = meshContainer.end();
601             mIt != mEndIt;
602             ++mIt, ++index )
603       {
604         if( slot.mAtlasId == mIt->mAtlasId )
605         {
606           // Append the mesh to the existing mesh and adjust any extents
607           Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
608
609           if( underlineGlyph )
610           {
611             AdjustExtents( extents,
612                            meshContainer,
613                            index,
614                            left,
615                            right,
616                            baseLine,
617                            underlinePosition,
618                            underlineThickness );
619           }
620
621           return;
622         }
623       }
624
625       // No mesh data object currently exists that references this atlas, so create a new one
626       MeshRecord meshRecord;
627       meshRecord.mAtlasId = slot.mAtlasId;
628       meshRecord.mMesh = newMesh;
629       meshContainer.push_back( meshRecord );
630
631       if( underlineGlyph )
632       {
633         // Adjust extents for this new meshrecord
634         AdjustExtents( extents,
635                        meshContainer,
636                        meshContainer.size() - 1u,
637                        left,
638                        right,
639                        baseLine,
640                        underlinePosition,
641                        underlineThickness );
642       }
643     }
644   }
645
646   void AdjustExtents( Vector< Extent >& extents,
647                       std::vector< MeshRecord>& meshRecords,
648                       uint32_t index,
649                       float left,
650                       float right,
651                       float baseLine,
652                       float underlinePosition,
653                       float underlineThickness )
654   {
655     bool foundExtent = false;
656     for ( Vector< Extent >::Iterator eIt = extents.Begin(),
657             eEndIt = extents.End();
658           eIt != eEndIt;
659           ++eIt )
660     {
661       if ( Equals( baseLine, eIt->mBaseLine ) )
662       {
663         foundExtent = true;
664         if ( left < eIt->mLeft )
665         {
666           eIt->mLeft = left;
667         }
668         if ( right > eIt->mRight  )
669         {
670           eIt->mRight = right;
671         }
672
673         if ( underlinePosition > eIt->mUnderlinePosition )
674         {
675           eIt->mUnderlinePosition = underlinePosition;
676         }
677         if ( underlineThickness > eIt->mUnderlineThickness )
678         {
679           eIt->mUnderlineThickness = underlineThickness;
680         }
681       }
682     }
683     if ( !foundExtent )
684     {
685       Extent extent;
686       extent.mLeft = left;
687       extent.mRight = right;
688       extent.mBaseLine = baseLine;
689       extent.mUnderlinePosition = underlinePosition;
690       extent.mUnderlineThickness = underlineThickness;
691       extent.mMeshRecordIndex = index;
692       extents.PushBack( extent );
693     }
694   }
695
696   void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
697   {
698     for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
699            glyphEndIt = glyphs.End();
700          glyphIt != glyphEndIt;
701          ++glyphIt )
702     {
703       const FontId fontId = (*glyphIt).fontId;
704       bool foundFont = false;
705
706       for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
707              blockEndIt = mBlockSizes.end();
708            blockIt != blockEndIt;
709            ++blockIt )
710       {
711         if( (*blockIt).mFontId == fontId )
712         {
713           foundFont = true;
714           break;
715         }
716       }
717
718       if ( !foundFont )
719       {
720         FontMetrics fontMetrics;
721         mFontClient.GetFontMetrics( fontId, fontMetrics );
722
723         MaxBlockSize maxBlockSize;
724         maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
725         maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
726         maxBlockSize.mFontId = fontId;
727
728         mBlockSizes.push_back( maxBlockSize );
729       }
730     }
731   }
732
733   void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
734                            Vector< Extent >& extents,
735                            const Vector4& underlineColor )
736   {
737     AtlasManager::Mesh2D newMesh;
738     unsigned short faceIndex = 0;
739     for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
740             eEndIt = extents.End();
741           eIt != eEndIt;
742           ++eIt )
743     {
744       AtlasManager::Vertex2D vert;
745       uint32_t index = eIt->mMeshRecordIndex;
746       Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
747
748       // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
749       float u = HALF / uv.x;
750       float v = HALF / uv.y;
751       float thickness = eIt->mUnderlineThickness;
752       float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
753       float tlx = eIt->mLeft;
754       float brx = eIt->mRight;
755
756       vert.mPosition.x = tlx;
757       vert.mPosition.y = baseLine;
758       vert.mTexCoords.x = ZERO;
759       vert.mTexCoords.y = ZERO;
760       vert.mColor = underlineColor;
761       newMesh.mVertices.PushBack( vert );
762
763       vert.mPosition.x = brx;
764       vert.mPosition.y = baseLine;
765       vert.mTexCoords.x = u;
766       vert.mColor = underlineColor;
767       newMesh.mVertices.PushBack( vert );
768
769       vert.mPosition.x = tlx;
770       vert.mPosition.y = baseLine + thickness;
771       vert.mTexCoords.x = ZERO;
772       vert.mTexCoords.y = v;
773       vert.mColor = underlineColor;
774       newMesh.mVertices.PushBack( vert );
775
776       vert.mPosition.x = brx;
777       vert.mPosition.y = baseLine + thickness;
778       vert.mTexCoords.x = u;
779       vert.mColor = underlineColor;
780       newMesh.mVertices.PushBack( vert );
781
782       // Six indices in counter clockwise winding
783       newMesh.mIndices.PushBack( faceIndex + 1u );
784       newMesh.mIndices.PushBack( faceIndex );
785       newMesh.mIndices.PushBack( faceIndex + 2u );
786       newMesh.mIndices.PushBack( faceIndex + 2u );
787       newMesh.mIndices.PushBack( faceIndex + 3u );
788       newMesh.mIndices.PushBack( faceIndex + 1u );
789       faceIndex += 4;
790
791       Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
792     }
793   }
794
795   Actor mActor;                                       ///< The actor parent which renders the text
796   AtlasGlyphManager mGlyphManager;                    ///< Glyph Manager to handle upload and caching
797   TextAbstraction::FontClient mFontClient;            ///< The font client used to supply glyph information
798   Shader mShaderL8;                                   ///< The shader for glyphs and emoji's shadows.
799   Shader mShaderRgba;                                 ///< The shader for emojis.
800   std::vector< MaxBlockSize > mBlockSizes;            ///< Maximum size needed to contain a glyph in a block within a new atlas
801   Vector< TextCacheEntry > mTextCache;                ///< Caches data from previous render
802   Property::Map mQuadVertexFormat;                    ///< Describes the vertex format for text
803   int mDepth;                                         ///< DepthIndex passed by control when connect to stage
804 };
805
806 Text::RendererPtr AtlasRenderer::New()
807 {
808   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
809
810   return Text::RendererPtr( new AtlasRenderer() );
811 }
812
813 Actor AtlasRenderer::Render( Text::ViewInterface& view,
814                              float& alignmentOffset,
815                              int depth )
816 {
817   DALI_LOG_INFO( gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n" );
818
819   UnparentAndReset( mImpl->mActor );
820
821   Length numberOfGlyphs = view.GetNumberOfGlyphs();
822
823   if( numberOfGlyphs > 0u )
824   {
825     Vector<GlyphInfo> glyphs;
826     glyphs.Resize( numberOfGlyphs );
827
828     Vector<Vector2> positions;
829     positions.Resize( numberOfGlyphs );
830
831     numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
832                                      positions.Begin(),
833                                      alignmentOffset,
834                                      0u,
835                                      numberOfGlyphs );
836
837     glyphs.Resize( numberOfGlyphs );
838     positions.Resize( numberOfGlyphs );
839
840     const Vector4* const colorsBuffer = view.GetColors();
841     const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
842     const Vector4& defaultColor = view.GetTextColor();
843
844     mImpl->AddGlyphs( view,
845                       positions,
846                       glyphs,
847                       defaultColor,
848                       colorsBuffer,
849                       colorIndicesBuffer,
850                       depth,
851                       alignmentOffset );
852
853     /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
854     /* This renderable actor is used to position the text, other "decorations" can rely on there always being an Actor regardless of it is whitespace or regular text. */
855     if ( !mImpl->mActor )
856     {
857       mImpl->mActor = Actor::New();
858     }
859   }
860
861   return mImpl->mActor;
862 }
863
864 AtlasRenderer::AtlasRenderer()
865 {
866   mImpl = new Impl();
867
868 }
869
870 AtlasRenderer::~AtlasRenderer()
871 {
872   mImpl->RemoveText();
873   delete mImpl;
874 }