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& textSize( view.GetLayoutSize() );
180 const Vector2 halfTextSize( textSize * 0.5f );
181 const Vector2& shadowOffset( view.GetShadowOffset() );
182 const Vector4& shadowColor( view.GetShadowColor() );
183 const bool underlineEnabled( view.IsUnderlineEnabled() );
184 const Vector4& underlineColor( view.GetUnderlineColor() );
185 const float underlineHeight( view.GetUnderlineHeight() );
187 // Get the underline runs.
188 const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
189 Vector<GlyphRun> underlineRuns;
190 underlineRuns.Resize( numberOfUnderlineRuns );
191 view.GetUnderlineRuns( underlineRuns.Begin(),
193 numberOfUnderlineRuns );
195 bool thereAreUnderlinedGlyphs = false;
197 float currentUnderlinePosition = ZERO;
198 float currentUnderlineThickness = underlineHeight;
199 uint32_t currentBlockSize = 0;
200 FontId lastFontId = 0;
201 FontId lastUnderlinedFontId = 0;
202 Style style = STYLE_NORMAL;
204 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
206 style = STYLE_DROP_SHADOW;
209 CalculateBlocksSize( glyphs );
211 // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
212 Vector< TextCacheEntry > newTextCache;
213 const GlyphInfo* const glyphsBuffer = glyphs.Begin();
214 const Vector2* const positionsBuffer = positions.Begin();
215 const Vector4* const colorsBuffer = colors.Begin();
217 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
219 const GlyphInfo& glyph = *( glyphsBuffer + i );
221 const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
222 thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
224 // No operation for white space
225 if( glyph.width && glyph.height )
227 // Are we still using the same fontId as previous
228 if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
230 // We need to fetch fresh font underline metrics
231 FontMetrics fontMetrics;
232 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
233 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
234 const float descender = ceil( fabsf( fontMetrics.descender ) );
236 if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
238 currentUnderlineThickness = fontMetrics.underlineThickness;
240 // Ensure underline will be at least a pixel high
241 if ( currentUnderlineThickness < ONE )
243 currentUnderlineThickness = ONE;
247 currentUnderlineThickness = ceil( currentUnderlineThickness );
251 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
252 if( currentUnderlinePosition > descender )
254 currentUnderlinePosition = descender;
257 if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
259 // Move offset down by one ( EFL behavior )
260 currentUnderlinePosition = ONE;
263 lastUnderlinedFontId = glyph.fontId;
266 if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
268 // Select correct size for new atlas if needed....?
269 if( lastFontId != glyph.fontId )
272 for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
273 endIt = mBlockSizes.end();
277 const MaxBlockSize& blockSize = *it;
278 if( blockSize.mFontId == glyph.fontId )
280 currentBlockSize = index;
281 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
282 DEFAULT_ATLAS_HEIGHT,
283 blockSize.mNeededBlockWidth,
284 blockSize.mNeededBlockHeight );
289 // Create a new image for the glyph
290 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
293 MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
295 // Ensure that the next image will fit into the current block size
296 bool setSize = false;
297 if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
300 blockSize.mNeededBlockWidth = bitmap.GetWidth();
302 if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
305 blockSize.mNeededBlockHeight = bitmap.GetHeight();
310 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
311 DEFAULT_ATLAS_HEIGHT,
312 blockSize.mNeededBlockWidth,
313 blockSize.mNeededBlockHeight );
316 // Locate a new slot for our glyph
317 mGlyphManager.Add( glyph, bitmap, slot );
322 // We have 2+ copies of the same glyph
323 mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
326 // Move the origin (0,0) of the mesh to the center of the actor
327 const Vector2 position = *( positionsBuffer + i ) - halfTextSize;
329 // Generate mesh data for this quad, plugging in our supplied position
330 AtlasManager::Mesh2D newMesh;
331 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
332 textCacheEntry.mFontId = glyph.fontId;
333 textCacheEntry.mImageId = slot.mImageId;
334 textCacheEntry.mIndex = glyph.index;
335 newTextCache.PushBack( textCacheEntry );
337 AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
339 // Adjust the vertices if the fixed-size font should be down-scaled
340 if( glyph.scaleFactor > 0 )
342 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
346 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
348 // Set the position of the vertex.
349 vertex.mPosition.x = position.x + ( ( vertex.mPosition.x - position.x ) * glyph.scaleFactor );
350 vertex.mPosition.y = position.y + ( ( vertex.mPosition.y - position.y ) * glyph.scaleFactor );
354 // Get the color of the character.
355 const Vector4& color = *( colorsBuffer + i );
357 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
361 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
363 // Set the color of the vertex.
364 vertex.mColor = color;
367 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
368 StitchTextMesh( meshContainer,
371 position.y + glyph.yBearing,
373 currentUnderlinePosition,
374 currentUnderlineThickness,
376 lastFontId = glyph.fontId;
380 // Now remove references for the old text
382 mTextCache.Swap( newTextCache );
384 if( thereAreUnderlinedGlyphs )
386 // Check to see if any of the text needs an underline
387 GenerateUnderlines( meshContainer, extents, underlineColor );
390 // For each MeshData object, create a mesh actor and add to the renderable actor
391 if( !meshContainer.empty() )
393 for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
394 endIt = meshContainer.end();
397 MeshRecord& meshRecord = *it;
399 Actor actor = CreateMeshActor( meshRecord, textSize );
401 // Create an effect if necessary
402 if( style == STYLE_DROP_SHADOW )
404 // Change the color of the vertices.
405 for( Vector<AtlasManager::Vertex2D>::Iterator vIt = meshRecord.mMesh.mVertices.Begin(),
406 vEndIt = meshRecord.mMesh.mVertices.End();
410 AtlasManager::Vertex2D& vertex = *vIt;
412 vertex.mColor = shadowColor;
415 // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
416 Actor containerActor = Actor::New();
417 containerActor.SetParentOrigin( ParentOrigin::CENTER );
418 containerActor.SetSize( actorSize );
420 Actor shadowActor = CreateMeshActor( meshRecord, textSize );
421 #if defined(DEBUG_ENABLED)
422 shadowActor.SetName( "Text Shadow renderable actor" );
424 // Offset shadow in x and y
425 shadowActor.RegisterProperty("uOffset", shadowOffset );
426 if( actor.GetRendererCount() )
428 Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
429 int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
430 renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
431 containerActor.Add( shadowActor );
432 containerActor.Add( actor );
433 actor = containerActor;
447 #if defined(DEBUG_ENABLED)
448 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
449 DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
451 metrics.mAtlasMetrics.mAtlasCount,
452 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
454 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
456 for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
458 DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
459 i + 1, i > 8 ? "" : " ",
460 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
461 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
462 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
463 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
464 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
465 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
466 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
473 for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
475 mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
477 mTextCache.Resize( 0 );
480 Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
482 PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat );
483 PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat );
484 quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
485 quadIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ), meshRecord.mMesh.mIndices.Size() );
487 Geometry quadGeometry = Geometry::New();
488 quadGeometry.AddVertexBuffer( quadVertices );
489 quadGeometry.SetIndexBuffer( quadIndices );
491 TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
492 Shader shader( mGlyphManager.GetShader( meshRecord.mAtlasId ) );
493 Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
494 renderer.SetTextures( textureSet );
495 renderer.SetProperty( Dali::Renderer::Property::BLENDING_MODE, BlendingMode::ON );
496 renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
497 Actor actor = Actor::New();
498 #if defined(DEBUG_ENABLED)
499 actor.SetName( "Text renderable actor" );
501 actor.AddRenderer( renderer );
503 // Keep all of the origins aligned
504 actor.SetParentOrigin( ParentOrigin::TOP_LEFT );
505 actor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
507 actor.SetSize( actorSize );
508 actor.RegisterProperty("uOffset", Vector2::ZERO );
512 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
513 AtlasManager::Mesh2D& newMesh,
514 Vector< Extent >& extents,
517 float underlinePosition,
518 float underlineThickness,
519 AtlasManager::AtlasSlot& slot )
523 float left = newMesh.mVertices[ 0 ].mPosition.x;
524 float right = newMesh.mVertices[ 1 ].mPosition.x;
526 // Check to see if there's a mesh data object that references the same atlas ?
528 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
529 mEndIt = meshContainer.end();
533 if( slot.mAtlasId == mIt->mAtlasId )
535 // Append the mesh to the existing mesh and adjust any extents
536 Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
540 AdjustExtents( extents,
547 underlineThickness );
554 // No mesh data object currently exists that references this atlas, so create a new one
555 MeshRecord meshRecord;
556 meshRecord.mAtlasId = slot.mAtlasId;
557 meshRecord.mMesh = newMesh;
558 meshContainer.push_back( meshRecord );
562 // Adjust extents for this new meshrecord
563 AdjustExtents( extents,
565 meshContainer.size() - 1u,
570 underlineThickness );
575 void AdjustExtents( Vector< Extent >& extents,
576 std::vector< MeshRecord>& meshRecords,
581 float underlinePosition,
582 float underlineThickness )
584 bool foundExtent = false;
585 for ( Vector< Extent >::Iterator eIt = extents.Begin(),
586 eEndIt = extents.End();
590 if ( Equals( baseLine, eIt->mBaseLine ) )
593 if ( left < eIt->mLeft )
597 if ( right > eIt->mRight )
602 if ( underlinePosition > eIt->mUnderlinePosition )
604 eIt->mUnderlinePosition = underlinePosition;
606 if ( underlineThickness > eIt->mUnderlineThickness )
608 eIt->mUnderlineThickness = underlineThickness;
616 extent.mRight = right;
617 extent.mBaseLine = baseLine;
618 extent.mUnderlinePosition = underlinePosition;
619 extent.mUnderlineThickness = underlineThickness;
620 extent.mMeshRecordIndex = index;
621 extents.PushBack( extent );
625 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
627 for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
628 glyphEndIt = glyphs.End();
629 glyphIt != glyphEndIt;
632 const FontId fontId = (*glyphIt).fontId;
633 bool foundFont = false;
635 for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
636 blockEndIt = mBlockSizes.end();
637 blockIt != blockEndIt;
640 if( (*blockIt).mFontId == fontId )
649 FontMetrics fontMetrics;
650 mFontClient.GetFontMetrics( fontId, fontMetrics );
652 MaxBlockSize maxBlockSize;
653 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
654 maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
655 maxBlockSize.mFontId = fontId;
657 mBlockSizes.push_back( maxBlockSize );
662 void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
663 Vector< Extent >& extents,
664 const Vector4& underlineColor )
666 AtlasManager::Mesh2D newMesh;
667 unsigned short faceIndex = 0;
668 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
669 eEndIt = extents.End();
673 AtlasManager::Vertex2D vert;
674 uint32_t index = eIt->mMeshRecordIndex;
675 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
677 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
678 float u = HALF / uv.x;
679 float v = HALF / uv.y;
680 float thickness = eIt->mUnderlineThickness;
681 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
682 float tlx = eIt->mLeft;
683 float brx = eIt->mRight;
685 vert.mPosition.x = tlx;
686 vert.mPosition.y = baseLine;
687 vert.mTexCoords.x = ZERO;
688 vert.mTexCoords.y = ZERO;
689 newMesh.mVertices.PushBack( vert );
691 vert.mPosition.x = brx;
692 vert.mPosition.y = baseLine;
693 vert.mTexCoords.x = u;
694 newMesh.mVertices.PushBack( vert );
696 vert.mPosition.x = tlx;
697 vert.mPosition.y = baseLine + thickness;
698 vert.mTexCoords.x = ZERO;
699 vert.mTexCoords.y = v;
700 newMesh.mVertices.PushBack( vert );
702 vert.mPosition.x = brx;
703 vert.mPosition.y = baseLine + thickness;
704 vert.mTexCoords.x = u;
705 newMesh.mVertices.PushBack( vert );
707 // Six indices in counter clockwise winding
708 newMesh.mIndices.PushBack( faceIndex + 1u );
709 newMesh.mIndices.PushBack( faceIndex );
710 newMesh.mIndices.PushBack( faceIndex + 2u );
711 newMesh.mIndices.PushBack( faceIndex + 2u );
712 newMesh.mIndices.PushBack( faceIndex + 3u );
713 newMesh.mIndices.PushBack( faceIndex + 1u );
716 vert.mColor = underlineColor;
718 Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
722 Actor mActor; ///< The actor parent which renders the text
723 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
724 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
725 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
726 Vector< TextCacheEntry > mTextCache; ///> Caches data from previous render
727 Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
728 Property::Map mQuadIndexFormat; ///> Describes the index format for text
729 int mDepth; ///> DepthIndex passed by control when connect to stage
732 Text::RendererPtr AtlasRenderer::New()
734 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
736 return Text::RendererPtr( new AtlasRenderer() );
739 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
741 UnparentAndReset( mImpl->mActor );
743 Length numberOfGlyphs = view.GetNumberOfGlyphs();
745 if( numberOfGlyphs > 0u )
747 Vector<GlyphInfo> glyphs;
748 glyphs.Resize( numberOfGlyphs );
750 Vector<Vector2> positions;
751 positions.Resize( numberOfGlyphs );
753 Vector<Vector4> colors;
754 colors.Resize( numberOfGlyphs, view.GetTextColor() );
756 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
762 glyphs.Resize( numberOfGlyphs );
763 positions.Resize( numberOfGlyphs );
764 colors.Resize( numberOfGlyphs );
766 mImpl->AddGlyphs( view,
772 /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
773 /* 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. */
774 if ( !mImpl->mActor )
776 mImpl->mActor = Actor::New();
780 return mImpl->mActor;
783 AtlasRenderer::AtlasRenderer()
789 AtlasRenderer::~AtlasRenderer()