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