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