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