2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/devel-api/rendering/renderer.h>
24 #include <dali/devel-api/rendering/geometry.h>
25 #include <dali/devel-api/text-abstraction/font-client.h>
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>
35 using namespace Dali::Toolkit;
36 using namespace Dali::Toolkit::Text;
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
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;
51 struct AtlasRenderer::Impl
67 AtlasManager::Mesh2D mMesh;
68 FrameBufferImage mBuffer;
72 * brief Struct used to generate the underline mesh.
73 * There is one Extent per line of text.
81 mUnderlinePosition( 0.0f ),
82 mUnderlineThickness( 0.0f ),
83 mMeshRecordIndex( 0u )
90 float mUnderlinePosition;
91 float mUnderlineThickness;
92 uint32_t mMeshRecordIndex;
99 mNeededBlockWidth( 0 ),
100 mNeededBlockHeight( 0 )
105 uint32_t mNeededBlockWidth;
106 uint32_t mNeededBlockHeight;
118 Text::GlyphIndex mIndex;
121 struct TextCacheEntry
131 Text::GlyphIndex mIndex;
138 mGlyphManager = AtlasGlyphManager::Get();
139 mFontClient = TextAbstraction::FontClient::Get();
141 mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
142 mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
143 mQuadVertexFormat[ "aColor" ] = Property::VECTOR4;
144 mQuadIndexFormat[ "indices" ] = Property::INTEGER;
147 bool IsGlyphUnderlined( GlyphIndex index,
148 const Vector<GlyphRun>& underlineRuns )
150 for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
151 endIt = underlineRuns.End();
155 const GlyphRun& run = *it;
157 if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
166 void AddGlyphs( Text::ViewInterface& view,
167 const Vector<Vector2>& positions,
168 const Vector<GlyphInfo>& glyphs,
169 const Vector<Vector4>& colors,
172 AtlasManager::AtlasSlot slot;
173 std::vector< MeshRecord > meshContainer;
174 Vector< Extent > extents;
175 TextCacheEntry textCacheEntry;
178 const Vector2& actorSize( view.GetControlSize() );
179 const Vector2 halfActorSize( actorSize * 0.5f );
180 const Vector2& shadowOffset( view.GetShadowOffset() );
181 const Vector4& shadowColor( view.GetShadowColor() );
182 const bool underlineEnabled( view.IsUnderlineEnabled() );
183 const Vector4& underlineColor( view.GetUnderlineColor() );
184 const float underlineHeight( view.GetUnderlineHeight() );
186 // Get the underline runs.
187 const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
188 Vector<GlyphRun> underlineRuns;
189 underlineRuns.Resize( numberOfUnderlineRuns );
190 view.GetUnderlineRuns( underlineRuns.Begin(),
192 numberOfUnderlineRuns );
194 bool thereAreUnderlinedGlyphs = false;
196 float currentUnderlinePosition = ZERO;
197 float currentUnderlineThickness = underlineHeight;
198 uint32_t currentBlockSize = 0;
199 FontId lastFontId = 0;
200 FontId lastUnderlinedFontId = 0;
201 Style style = STYLE_NORMAL;
203 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
205 style = STYLE_DROP_SHADOW;
208 CalculateBlocksSize( glyphs );
210 // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
211 Vector< TextCacheEntry > newTextCache;
212 const GlyphInfo* const glyphsBuffer = glyphs.Begin();
213 const Vector2* const positionsBuffer = positions.Begin();
214 const Vector4* const colorsBuffer = colors.Begin();
216 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
218 const GlyphInfo& glyph = *( glyphsBuffer + i );
220 const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
221 thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
223 // No operation for white space
224 if( glyph.width && glyph.height )
226 // Are we still using the same fontId as previous
227 if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
229 // We need to fetch fresh font underline metrics
230 FontMetrics fontMetrics;
231 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
232 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
233 const float descender = ceil( fabsf( fontMetrics.descender ) );
235 if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
237 currentUnderlineThickness = fontMetrics.underlineThickness;
239 // Ensure underline will be at least a pixel high
240 if ( currentUnderlineThickness < ONE )
242 currentUnderlineThickness = ONE;
246 currentUnderlineThickness = ceil( currentUnderlineThickness );
250 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
251 if( currentUnderlinePosition > descender )
253 currentUnderlinePosition = descender;
256 if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
258 // Move offset down by one ( EFL behavior )
259 currentUnderlinePosition = ONE;
262 lastUnderlinedFontId = glyph.fontId;
265 if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
267 // Select correct size for new atlas if needed....?
268 if( lastFontId != glyph.fontId )
271 for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
272 endIt = mBlockSizes.end();
276 const MaxBlockSize& blockSize = *it;
277 if( blockSize.mFontId == glyph.fontId )
279 currentBlockSize = index;
280 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
281 DEFAULT_ATLAS_HEIGHT,
282 blockSize.mNeededBlockWidth,
283 blockSize.mNeededBlockHeight );
288 // Create a new image for the glyph
289 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
292 MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
294 // Ensure that the next image will fit into the current block size
295 bool setSize = false;
296 if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
299 blockSize.mNeededBlockWidth = bitmap.GetWidth();
301 if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
304 blockSize.mNeededBlockHeight = bitmap.GetHeight();
309 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
310 DEFAULT_ATLAS_HEIGHT,
311 blockSize.mNeededBlockWidth,
312 blockSize.mNeededBlockHeight );
315 // Locate a new slot for our glyph
316 mGlyphManager.Add( glyph, bitmap, slot );
321 // We have 2+ copies of the same glyph
322 mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
325 // Move the origin (0,0) of the mesh to the center of the actor
326 const Vector2 position = *( positionsBuffer + i ) - halfActorSize;
328 // Generate mesh data for this quad, plugging in our supplied position
329 AtlasManager::Mesh2D newMesh;
330 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
331 textCacheEntry.mFontId = glyph.fontId;
332 textCacheEntry.mImageId = slot.mImageId;
333 textCacheEntry.mIndex = glyph.index;
334 newTextCache.PushBack( textCacheEntry );
336 AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
338 // Adjust the vertices if the fixed-size font should be down-scaled
339 if( glyph.scaleFactor > 0 )
341 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
345 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
347 // Set the position of the vertex.
348 vertex.mPosition.x = position.x + ( ( vertex.mPosition.x - position.x ) * glyph.scaleFactor );
349 vertex.mPosition.y = position.y + ( ( vertex.mPosition.y - position.y ) * glyph.scaleFactor );
353 // Get the color of the character.
354 const Vector4& color = *( colorsBuffer + i );
356 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
360 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
362 // Set the color of the vertex.
363 vertex.mColor = color;
366 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
367 StitchTextMesh( meshContainer,
370 position.y + glyph.yBearing,
372 currentUnderlinePosition,
373 currentUnderlineThickness,
375 lastFontId = glyph.fontId;
379 // Now remove references for the old text
381 mTextCache.Swap( newTextCache );
383 if( thereAreUnderlinedGlyphs )
385 // Check to see if any of the text needs an underline
386 GenerateUnderlines( meshContainer, extents, underlineColor );
389 // For each MeshData object, create a mesh actor and add to the renderable actor
390 if( !meshContainer.empty() )
392 for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
393 endIt = meshContainer.end();
396 MeshRecord& meshRecord = *it;
398 Actor actor = CreateMeshActor( meshRecord, actorSize );
400 // Create an effect if necessary
401 if( style == STYLE_DROP_SHADOW )
403 // Change the color of the vertices.
404 for( Vector<AtlasManager::Vertex2D>::Iterator vIt = meshRecord.mMesh.mVertices.Begin(),
405 vEndIt = meshRecord.mMesh.mVertices.End();
409 AtlasManager::Vertex2D& vertex = *vIt;
411 vertex.mColor = shadowColor;
414 // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
415 Actor containerActor = Actor::New();
416 containerActor.SetParentOrigin( ParentOrigin::CENTER );
417 containerActor.SetSize( actorSize );
419 Actor shadowActor = CreateMeshActor( meshRecord, actorSize );
420 #if defined(DEBUG_ENABLED)
421 shadowActor.SetName( "Text Shadow renderable actor" );
423 // Offset shadow in x and y
424 shadowActor.RegisterProperty("uOffset", shadowOffset );
425 if( actor.GetRendererCount() )
427 Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
428 int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
429 renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
430 shadowActor.SetParentOrigin( ParentOrigin::CENTER );
431 shadowActor.SetSize( actorSize );
432 containerActor.Add( shadowActor );
433 containerActor.Add( actor );
434 actor = containerActor;
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",
452 metrics.mAtlasMetrics.mAtlasCount,
453 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
455 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
457 for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
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 );
474 for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
476 mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
478 mTextCache.Resize( 0 );
481 Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
483 PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat, meshRecord.mMesh.mVertices.Size() );
484 PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat, meshRecord.mMesh.mIndices.Size() );
485 quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ) );
486 quadIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ) );
488 Geometry quadGeometry = Geometry::New();
489 quadGeometry.AddVertexBuffer( quadVertices );
490 quadGeometry.SetIndexBuffer( quadIndices );
492 Material material = mGlyphManager.GetMaterial( meshRecord.mAtlasId );
493 Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, material );
494 renderer.SetProperty( Dali::Renderer::Property::BLENDING_MODE, BlendingMode::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" );
500 actor.AddRenderer( renderer );
501 actor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
502 actor.SetSize( actorSize );
503 actor.RegisterProperty("uOffset", Vector2::ZERO );
507 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
508 AtlasManager::Mesh2D& newMesh,
509 Vector< Extent >& extents,
512 float underlinePosition,
513 float underlineThickness,
514 AtlasManager::AtlasSlot& slot )
518 float left = newMesh.mVertices[ 0 ].mPosition.x;
519 float right = newMesh.mVertices[ 1 ].mPosition.x;
521 // Check to see if there's a mesh data object that references the same atlas ?
523 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
524 mEndIt = meshContainer.end();
528 if( slot.mAtlasId == mIt->mAtlasId )
530 // Append the mesh to the existing mesh and adjust any extents
531 Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
535 AdjustExtents( extents,
542 underlineThickness );
549 // No mesh data object currently exists that references this atlas, so create a new one
550 MeshRecord meshRecord;
551 meshRecord.mAtlasId = slot.mAtlasId;
552 meshRecord.mMesh = newMesh;
553 meshContainer.push_back( meshRecord );
557 // Adjust extents for this new meshrecord
558 AdjustExtents( extents,
560 meshContainer.size() - 1u,
565 underlineThickness );
570 void AdjustExtents( Vector< Extent >& extents,
571 std::vector< MeshRecord>& meshRecords,
576 float underlinePosition,
577 float underlineThickness )
579 bool foundExtent = false;
580 for ( Vector< Extent >::Iterator eIt = extents.Begin(),
581 eEndIt = extents.End();
585 if ( Equals( baseLine, eIt->mBaseLine ) )
588 if ( left < eIt->mLeft )
592 if ( right > eIt->mRight )
597 if ( underlinePosition > eIt->mUnderlinePosition )
599 eIt->mUnderlinePosition = underlinePosition;
601 if ( underlineThickness > eIt->mUnderlineThickness )
603 eIt->mUnderlineThickness = underlineThickness;
611 extent.mRight = right;
612 extent.mBaseLine = baseLine;
613 extent.mUnderlinePosition = underlinePosition;
614 extent.mUnderlineThickness = underlineThickness;
615 extent.mMeshRecordIndex = index;
616 extents.PushBack( extent );
620 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
622 for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
623 glyphEndIt = glyphs.End();
624 glyphIt != glyphEndIt;
627 const FontId fontId = (*glyphIt).fontId;
628 bool foundFont = false;
630 for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
631 blockEndIt = mBlockSizes.end();
632 blockIt != blockEndIt;
635 if( (*blockIt).mFontId == fontId )
644 FontMetrics fontMetrics;
645 mFontClient.GetFontMetrics( fontId, fontMetrics );
647 MaxBlockSize maxBlockSize;
648 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
649 maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
650 maxBlockSize.mFontId = fontId;
652 mBlockSizes.push_back( maxBlockSize );
657 void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
658 Vector< Extent >& extents,
659 const Vector4& underlineColor )
661 AtlasManager::Mesh2D newMesh;
662 unsigned short faceIndex = 0;
663 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
664 eEndIt = extents.End();
668 AtlasManager::Vertex2D vert;
669 uint32_t index = eIt->mMeshRecordIndex;
670 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
672 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
673 float u = HALF / uv.x;
674 float v = HALF / uv.y;
675 float thickness = eIt->mUnderlineThickness;
676 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
677 float tlx = eIt->mLeft;
678 float brx = eIt->mRight;
680 vert.mPosition.x = tlx;
681 vert.mPosition.y = baseLine;
682 vert.mTexCoords.x = ZERO;
683 vert.mTexCoords.y = ZERO;
684 newMesh.mVertices.PushBack( vert );
686 vert.mPosition.x = brx;
687 vert.mPosition.y = baseLine;
688 vert.mTexCoords.x = u;
689 newMesh.mVertices.PushBack( vert );
691 vert.mPosition.x = tlx;
692 vert.mPosition.y = baseLine + thickness;
693 vert.mTexCoords.x = ZERO;
694 vert.mTexCoords.y = v;
695 newMesh.mVertices.PushBack( vert );
697 vert.mPosition.x = brx;
698 vert.mPosition.y = baseLine + thickness;
699 vert.mTexCoords.x = u;
700 newMesh.mVertices.PushBack( vert );
702 // Six indices in counter clockwise winding
703 newMesh.mIndices.PushBack( faceIndex + 1u );
704 newMesh.mIndices.PushBack( faceIndex );
705 newMesh.mIndices.PushBack( faceIndex + 2u );
706 newMesh.mIndices.PushBack( faceIndex + 2u );
707 newMesh.mIndices.PushBack( faceIndex + 3u );
708 newMesh.mIndices.PushBack( faceIndex + 1u );
711 vert.mColor = underlineColor;
713 Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
717 Actor mActor; ///< The actor parent which renders the text
718 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
719 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
720 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
721 Vector< TextCacheEntry > mTextCache; ///> Caches data from previous render
722 Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
723 Property::Map mQuadIndexFormat; ///> Describes the index format for text
724 int mDepth; ///> DepthIndex passed by control when connect to stage
727 Text::RendererPtr AtlasRenderer::New()
729 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
731 return Text::RendererPtr( new AtlasRenderer() );
734 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
736 UnparentAndReset( mImpl->mActor );
738 Length numberOfGlyphs = view.GetNumberOfGlyphs();
740 if( numberOfGlyphs > 0u )
742 Vector<GlyphInfo> glyphs;
743 glyphs.Resize( numberOfGlyphs );
745 Vector<Vector2> positions;
746 positions.Resize( numberOfGlyphs );
748 Vector<Vector4> colors;
749 colors.Resize( numberOfGlyphs, view.GetTextColor() );
751 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
757 glyphs.Resize( numberOfGlyphs );
758 positions.Resize( numberOfGlyphs );
759 colors.Resize( numberOfGlyphs );
761 mImpl->AddGlyphs( view,
767 /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
768 /* 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. */
769 if ( !mImpl->mActor )
771 mImpl->mActor = Actor::New();
775 return mImpl->mActor;
778 AtlasRenderer::AtlasRenderer()
784 AtlasRenderer::~AtlasRenderer()