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