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/public-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
62 : mColor( Color::BLACK ),
69 AtlasManager::Mesh2D mMesh;
70 FrameBufferImage mBuffer;
74 * brief Struct used to generate the underline mesh.
75 * There is one Extent per line of text.
83 mUnderlinePosition( 0.0f ),
84 mUnderlineThickness( 0.0f ),
92 float mUnderlinePosition;
93 float mUnderlineThickness;
94 uint32_t mMeshRecordIndex;
101 mNeededBlockWidth( 0 ),
102 mNeededBlockHeight( 0 )
107 uint32_t mNeededBlockWidth;
108 uint32_t mNeededBlockHeight;
120 Text::GlyphIndex mIndex;
123 struct TextCacheEntry
133 Text::GlyphIndex mIndex;
140 mGlyphManager = AtlasGlyphManager::Get();
141 mFontClient = TextAbstraction::FontClient::Get();
143 mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
144 mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
145 mQuadIndexFormat[ "indices" ] = Property::INTEGER;
148 bool IsGlyphUnderlined( GlyphIndex index,
149 const Vector<GlyphRun>& underlineRuns )
151 for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
152 endIt = underlineRuns.End();
156 const GlyphRun& run = *it;
158 if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
167 void AddGlyphs( Text::ViewInterface& view,
168 const Vector<Vector2>& positions,
169 const Vector<GlyphInfo>& glyphs,
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 Vector4& textColor( view.GetTextColor() );
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();
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;
255 if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
257 // Move offset down by one ( EFL behavior )
258 currentUnderlinePosition = ONE;
261 lastUnderlinedFontId = glyph.fontId;
264 if ( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
266 // Select correct size for new atlas if needed....?
267 if ( lastFontId != glyph.fontId )
269 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
271 if ( mBlockSizes[ j ].mFontId == glyph.fontId )
273 currentBlockSize = j;
274 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
275 DEFAULT_ATLAS_HEIGHT,
276 mBlockSizes[ j ].mNeededBlockWidth,
277 mBlockSizes[ j ].mNeededBlockHeight );
282 // Create a new image for the glyph
283 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
286 // Ensure that the next image will fit into the current block size
287 bool setSize = false;
288 if ( bitmap.GetWidth() > mBlockSizes[ currentBlockSize ].mNeededBlockWidth )
291 mBlockSizes[ currentBlockSize ].mNeededBlockWidth = bitmap.GetWidth();
293 if ( bitmap.GetHeight() > mBlockSizes[ currentBlockSize ].mNeededBlockHeight )
296 mBlockSizes[ currentBlockSize ].mNeededBlockHeight = bitmap.GetHeight();
301 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
302 DEFAULT_ATLAS_HEIGHT,
303 mBlockSizes[ currentBlockSize ].mNeededBlockWidth,
304 mBlockSizes[ currentBlockSize ].mNeededBlockHeight );
307 // Locate a new slot for our glyph
308 mGlyphManager.Add( glyph, bitmap, slot );
313 // We have 2+ copies of the same glyph
314 mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
317 // Move the origin (0,0) of the mesh to the center of the actor
318 Vector2 position = *( positionsBuffer + i ) - halfActorSize;
320 // Generate mesh data for this quad, plugging in our supplied position
321 AtlasManager::Mesh2D newMesh;
322 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
323 textCacheEntry.mFontId = glyph.fontId;
324 textCacheEntry.mImageId = slot.mImageId;
325 textCacheEntry.mIndex = glyph.index;
326 newTextCache.PushBack( textCacheEntry );
328 // Adjust the vertices if the fixed-size font should be down-scaled
329 if( glyph.scaleFactor > 0 )
331 for( unsigned int i=0; i<newMesh.mVertices.Count(); ++i )
333 newMesh.mVertices[i].mPosition.x = position.x + ( ( newMesh.mVertices[i].mPosition.x - position.x ) * glyph.scaleFactor );
334 newMesh.mVertices[i].mPosition.y = position.y + ( ( newMesh.mVertices[i].mPosition.y - position.y ) * glyph.scaleFactor );
338 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
339 StitchTextMesh( meshContainer,
343 position.y + glyph.yBearing,
345 currentUnderlinePosition,
346 currentUnderlineThickness,
348 lastFontId = glyph.fontId;
352 // Now remove references for the old text
354 mTextCache.Swap( newTextCache );
356 if( thereAreUnderlinedGlyphs )
358 // Check to see if any of the text needs an underline
359 GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
362 // For each MeshData object, create a mesh actor and add to the renderable actor
363 if ( meshContainer.size() )
365 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt )
367 Actor actor = CreateMeshActor( *mIt, actorSize );
369 // Create an effect if necessary
370 if ( style == STYLE_DROP_SHADOW )
372 // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
373 Actor containerActor = Actor::New();
374 containerActor.SetParentOrigin( ParentOrigin::CENTER );
375 containerActor.SetSize( actorSize );
377 Actor shadowActor = Actor::New();
378 #if defined(DEBUG_ENABLED)
379 shadowActor.SetName( "Text Shadow renderable actor" );
381 // Offset shadow in x and y
382 shadowActor.RegisterProperty("uOffset", shadowOffset );
383 if ( actor.GetRendererCount() )
385 Dali::Renderer renderer( actor.GetRendererAt( 0 ) );
386 Geometry geometry = renderer.GetGeometry();
387 Material material = renderer.GetMaterial();
389 Dali::Renderer shadowRenderer = Dali::Renderer::New( geometry, material );
390 shadowRenderer.SetDepthIndex( renderer.GetDepthIndex() - 1 );
391 shadowActor.AddRenderer( shadowRenderer );
392 shadowActor.SetParentOrigin( ParentOrigin::CENTER );
393 shadowActor.SetSize( actorSize );
394 shadowActor.SetColor( shadowColor );
395 containerActor.Add( shadowActor );
396 containerActor.Add( actor );
397 actor = containerActor;
411 #if defined(DEBUG_ENABLED)
412 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
413 DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
415 metrics.mAtlasMetrics.mAtlasCount,
416 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
418 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
420 for ( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
422 DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
423 i + 1, i > 8 ? "" : " ",
424 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
425 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
426 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
427 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
428 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
429 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
430 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
437 for ( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
439 mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
441 mTextCache.Resize( 0 );
444 Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
446 PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat, meshRecord.mMesh.mVertices.Size() );
447 PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat, meshRecord.mMesh.mIndices.Size() );
448 quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ) );
449 quadIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ) );
451 Geometry quadGeometry = Geometry::New();
452 quadGeometry.AddVertexBuffer( quadVertices );
453 quadGeometry.SetIndexBuffer( quadIndices );
455 Material material = mGlyphManager.GetMaterial( meshRecord.mAtlasId );
456 Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, material );
457 renderer.SetDepthIndex( CONTENT_DEPTH_INDEX + mDepth );
458 Actor actor = Actor::New();
459 #if defined(DEBUG_ENABLED)
460 actor.SetName( "Text renderable actor" );
462 actor.AddRenderer( renderer );
463 actor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
464 actor.SetSize( actorSize );
465 actor.SetColor( meshRecord.mColor );
466 actor.RegisterProperty("uOffset", Vector2::ZERO );
470 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
471 AtlasManager::Mesh2D& newMesh,
472 Vector< Extent >& extents,
473 const Vector4& color,
476 float underlinePosition,
477 float underlineThickness,
478 AtlasManager::AtlasSlot& slot )
482 float left = newMesh.mVertices[ 0 ].mPosition.x;
483 float right = newMesh.mVertices[ 1 ].mPosition.x;
485 // Check to see if there's a mesh data object that references the same atlas ?
487 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
488 mEndIt = meshContainer.end();
492 if ( slot.mAtlasId == mIt->mAtlasId && color == mIt->mColor )
494 // Append the mesh to the existing mesh and adjust any extents
495 Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
499 AdjustExtents( extents,
506 underlineThickness );
513 // No mesh data object currently exists that references this atlas, so create a new one
514 MeshRecord meshRecord;
515 meshRecord.mAtlasId = slot.mAtlasId;
516 meshRecord.mMesh = newMesh;
517 meshRecord.mColor = color;
518 meshContainer.push_back( meshRecord );
522 // Adjust extents for this new meshrecord
523 AdjustExtents( extents,
525 meshContainer.size() - 1u,
530 underlineThickness );
535 void AdjustExtents( Vector< Extent >& extents,
536 std::vector< MeshRecord>& meshRecords,
541 float underlinePosition,
542 float underlineThickness )
544 bool foundExtent = false;
545 for ( Vector< Extent >::Iterator eIt = extents.Begin(),
546 eEndIt = extents.End();
550 if ( Equals( baseLine, eIt->mBaseLine ) )
553 if ( left < eIt->mLeft )
557 if ( right > eIt->mRight )
562 if ( underlinePosition > eIt->mUnderlinePosition )
564 eIt->mUnderlinePosition = underlinePosition;
566 if ( underlineThickness > eIt->mUnderlineThickness )
568 eIt->mUnderlineThickness = underlineThickness;
576 extent.mRight = right;
577 extent.mBaseLine = baseLine;
578 extent.mUnderlinePosition = underlinePosition;
579 extent.mUnderlineThickness = underlineThickness;
580 extent.mMeshRecordIndex = index;
581 extents.PushBack( extent );
585 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
587 MaxBlockSize maxBlockSize;
588 for ( uint32_t i = 0; i < glyphs.Size(); ++i )
590 FontId fontId = glyphs[ i ].fontId;
591 bool foundFont = false;
592 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
594 if ( mBlockSizes[ j ].mFontId == fontId )
601 FontMetrics fontMetrics;
602 mFontClient.GetFontMetrics( fontId, fontMetrics );
603 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
604 maxBlockSize.mNeededBlockHeight = static_cast< uint32_t >( fontMetrics.height );
605 maxBlockSize.mFontId = fontId;
606 mBlockSizes.push_back( maxBlockSize );
611 void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
612 Vector< Extent >& extents,
613 const Vector4& underlineColor,
614 const Vector4& textColor )
616 AtlasManager::Mesh2D newMesh;
617 unsigned short faceIndex = 0;
618 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
619 eEndIt = extents.End();
623 AtlasManager::Vertex2D vert;
624 uint32_t index = eIt->mMeshRecordIndex;
625 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
627 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
628 float u = HALF / uv.x;
629 float v = HALF / uv.y;
630 float thickness = eIt->mUnderlineThickness;
631 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
632 float tlx = eIt->mLeft;
633 float brx = eIt->mRight;
635 vert.mPosition.x = tlx;
636 vert.mPosition.y = baseLine;
637 vert.mTexCoords.x = ZERO;
638 vert.mTexCoords.y = ZERO;
639 newMesh.mVertices.PushBack( vert );
641 vert.mPosition.x = brx;
642 vert.mPosition.y = baseLine;
643 vert.mTexCoords.x = u;
644 newMesh.mVertices.PushBack( vert );
646 vert.mPosition.x = tlx;
647 vert.mPosition.y = baseLine + thickness;
648 vert.mTexCoords.x = ZERO;
649 vert.mTexCoords.y = v;
650 newMesh.mVertices.PushBack( vert );
652 vert.mPosition.x = brx;
653 vert.mPosition.y = baseLine + thickness;
654 vert.mTexCoords.x = u;
655 newMesh.mVertices.PushBack( vert );
657 // Six indices in counter clockwise winding
658 newMesh.mIndices.PushBack( faceIndex + 1u );
659 newMesh.mIndices.PushBack( faceIndex );
660 newMesh.mIndices.PushBack( faceIndex + 2u );
661 newMesh.mIndices.PushBack( faceIndex + 2u );
662 newMesh.mIndices.PushBack( faceIndex + 3u );
663 newMesh.mIndices.PushBack( faceIndex + 1u );
666 if ( underlineColor == textColor )
668 Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
673 record.mMesh = newMesh;
674 record.mAtlasId = meshRecords[ index ].mAtlasId;
675 record.mColor = underlineColor;
676 meshRecords.push_back( record );
681 Actor mActor; ///< The actor parent which renders the text
682 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
683 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
684 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
685 Vector< TextCacheEntry > mTextCache; ///> Caches data from previous render
686 Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
687 Property::Map mQuadIndexFormat; ///> Describes the index format for text
688 int mDepth; ///> DepthIndex passed by control when connect to stage
691 Text::RendererPtr AtlasRenderer::New()
693 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
695 return Text::RendererPtr( new AtlasRenderer() );
698 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
700 UnparentAndReset( mImpl->mActor );
702 Length numberOfGlyphs = view.GetNumberOfGlyphs();
704 if( numberOfGlyphs > 0u )
706 Vector<GlyphInfo> glyphs;
707 glyphs.Resize( numberOfGlyphs );
709 Vector<Vector2> positions;
710 positions.Resize( numberOfGlyphs );
712 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
716 glyphs.Resize( numberOfGlyphs );
717 positions.Resize( numberOfGlyphs );
719 mImpl->AddGlyphs( view,
724 /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
725 /* 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*/
726 if ( !mImpl->mActor )
728 mImpl->mActor = Actor::New();
732 return mImpl->mActor;
735 AtlasRenderer::AtlasRenderer()
741 AtlasRenderer::~AtlasRenderer()