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;
146 bool IsGlyphUnderlined( GlyphIndex index,
147 const Vector<GlyphRun>& underlineRuns )
149 for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
150 endIt = underlineRuns.End();
154 const GlyphRun& run = *it;
156 if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
165 void AddGlyphs( Text::ViewInterface& view,
166 const Vector<Vector2>& positions,
167 const Vector<GlyphInfo>& glyphs,
168 const Vector4& defaultColor,
169 const Vector4* const colorsBuffer,
170 const ColorIndex* const colorIndicesBuffer,
173 AtlasManager::AtlasSlot slot;
174 std::vector< MeshRecord > meshContainer;
175 Vector< Extent > extents;
176 TextCacheEntry textCacheEntry;
179 const Vector2& actorSize( view.GetControlSize() );
180 const Vector2& textSize( view.GetLayoutSize() );
181 const Vector2 halfTextSize( textSize * 0.5f );
182 const Vector2& shadowOffset( view.GetShadowOffset() );
183 const Vector4& shadowColor( view.GetShadowColor() );
184 const bool underlineEnabled( view.IsUnderlineEnabled() );
185 const Vector4& underlineColor( view.GetUnderlineColor() );
186 const float underlineHeight( view.GetUnderlineHeight() );
188 const bool useDefaultColor = ( NULL == colorsBuffer );
190 // Get the underline runs.
191 const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
192 Vector<GlyphRun> underlineRuns;
193 underlineRuns.Resize( numberOfUnderlineRuns );
194 view.GetUnderlineRuns( underlineRuns.Begin(),
196 numberOfUnderlineRuns );
198 bool thereAreUnderlinedGlyphs = false;
200 float currentUnderlinePosition = ZERO;
201 float currentUnderlineThickness = underlineHeight;
202 uint32_t currentBlockSize = 0;
203 FontId lastFontId = 0;
204 FontId lastUnderlinedFontId = 0;
205 Style style = STYLE_NORMAL;
207 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
209 style = STYLE_DROP_SHADOW;
212 CalculateBlocksSize( glyphs );
214 // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
215 Vector< TextCacheEntry > newTextCache;
216 const GlyphInfo* const glyphsBuffer = glyphs.Begin();
217 const Vector2* const positionsBuffer = positions.Begin();
219 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
221 const GlyphInfo& glyph = *( glyphsBuffer + i );
223 const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
224 thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
226 // No operation for white space
227 if( glyph.width && glyph.height )
229 // Are we still using the same fontId as previous
230 if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
232 // We need to fetch fresh font underline metrics
233 FontMetrics fontMetrics;
234 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
235 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
236 const float descender = ceil( fabsf( fontMetrics.descender ) );
238 if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
240 currentUnderlineThickness = fontMetrics.underlineThickness;
242 // Ensure underline will be at least a pixel high
243 if ( currentUnderlineThickness < ONE )
245 currentUnderlineThickness = ONE;
249 currentUnderlineThickness = ceil( currentUnderlineThickness );
253 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
254 if( currentUnderlinePosition > descender )
256 currentUnderlinePosition = descender;
259 if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
261 // Move offset down by one ( EFL behavior )
262 currentUnderlinePosition = ONE;
265 lastUnderlinedFontId = glyph.fontId;
268 if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
270 // Select correct size for new atlas if needed....?
271 if( lastFontId != glyph.fontId )
274 for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
275 endIt = mBlockSizes.end();
279 const MaxBlockSize& blockSize = *it;
280 if( blockSize.mFontId == glyph.fontId )
282 currentBlockSize = index;
283 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
284 DEFAULT_ATLAS_HEIGHT,
285 blockSize.mNeededBlockWidth,
286 blockSize.mNeededBlockHeight );
291 // Create a new image for the glyph
292 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
295 MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
297 // Ensure that the next image will fit into the current block size
298 bool setSize = false;
299 if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
302 blockSize.mNeededBlockWidth = bitmap.GetWidth();
304 if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
307 blockSize.mNeededBlockHeight = bitmap.GetHeight();
312 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
313 DEFAULT_ATLAS_HEIGHT,
314 blockSize.mNeededBlockWidth,
315 blockSize.mNeededBlockHeight );
318 // Locate a new slot for our glyph
319 mGlyphManager.Add( glyph, bitmap, slot );
324 // We have 2+ copies of the same glyph
325 mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
328 // Move the origin (0,0) of the mesh to the center of the actor
329 const Vector2 position = *( positionsBuffer + i ) - halfTextSize;
331 // Generate mesh data for this quad, plugging in our supplied position
332 AtlasManager::Mesh2D newMesh;
333 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
334 textCacheEntry.mFontId = glyph.fontId;
335 textCacheEntry.mImageId = slot.mImageId;
336 textCacheEntry.mIndex = glyph.index;
337 newTextCache.PushBack( textCacheEntry );
339 AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
341 // Adjust the vertices if the fixed-size font should be down-scaled
342 if( glyph.scaleFactor > 0 )
344 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
348 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
350 // Set the position of the vertex.
351 vertex.mPosition.x = position.x + ( ( vertex.mPosition.x - position.x ) * glyph.scaleFactor );
352 vertex.mPosition.y = position.y + ( ( vertex.mPosition.y - position.y ) * glyph.scaleFactor );
356 // Get the color of the character.
357 const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i );
358 const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u );
360 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
364 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
366 // Set the color of the vertex.
367 vertex.mColor = color;
370 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
371 StitchTextMesh( meshContainer,
374 position.y + glyph.yBearing,
376 currentUnderlinePosition,
377 currentUnderlineThickness,
379 lastFontId = glyph.fontId;
383 // Now remove references for the old text
385 mTextCache.Swap( newTextCache );
387 if( thereAreUnderlinedGlyphs )
389 // Check to see if any of the text needs an underline
390 GenerateUnderlines( meshContainer, extents, underlineColor );
393 // For each MeshData object, create a mesh actor and add to the renderable actor
394 if( !meshContainer.empty() )
396 for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
397 endIt = meshContainer.end();
400 MeshRecord& meshRecord = *it;
402 Actor actor = CreateMeshActor( meshRecord, textSize );
404 // Create an effect if necessary
405 if( style == STYLE_DROP_SHADOW )
407 // Change the color of the vertices.
408 for( Vector<AtlasManager::Vertex2D>::Iterator vIt = meshRecord.mMesh.mVertices.Begin(),
409 vEndIt = meshRecord.mMesh.mVertices.End();
413 AtlasManager::Vertex2D& vertex = *vIt;
415 vertex.mColor = shadowColor;
418 // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
419 Actor containerActor = Actor::New();
420 containerActor.SetParentOrigin( ParentOrigin::CENTER );
421 containerActor.SetSize( actorSize );
423 Actor shadowActor = CreateMeshActor( meshRecord, textSize );
424 #if defined(DEBUG_ENABLED)
425 shadowActor.SetName( "Text Shadow renderable actor" );
427 // Offset shadow in x and y
428 shadowActor.RegisterProperty("uOffset", shadowOffset );
429 if( actor.GetRendererCount() )
431 Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
432 int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
433 renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
434 containerActor.Add( shadowActor );
435 containerActor.Add( actor );
436 actor = containerActor;
450 #if defined(DEBUG_ENABLED)
451 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
452 DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
454 metrics.mAtlasMetrics.mAtlasCount,
455 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
457 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
459 for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
461 DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
462 i + 1, i > 8 ? "" : " ",
463 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
464 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
465 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
466 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
467 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
468 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
469 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
476 for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
478 mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
480 mTextCache.Resize( 0 );
483 Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
485 PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat );
486 quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
488 Geometry quadGeometry = Geometry::New();
489 quadGeometry.AddVertexBuffer( quadVertices );
490 quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0], meshRecord.mMesh.mIndices.Size() );
492 TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
493 Shader shader( mGlyphManager.GetShader( meshRecord.mAtlasId ) );
494 Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
495 renderer.SetTextures( textureSet );
496 renderer.SetProperty( Dali::Renderer::Property::BLENDING_MODE, BlendingMode::ON );
497 renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
498 Actor actor = Actor::New();
499 #if defined(DEBUG_ENABLED)
500 actor.SetName( "Text renderable actor" );
502 actor.AddRenderer( renderer );
504 // Keep all of the origins aligned
505 actor.SetParentOrigin( ParentOrigin::TOP_LEFT );
506 actor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
508 actor.SetSize( actorSize );
509 actor.RegisterProperty("uOffset", Vector2::ZERO );
513 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
514 AtlasManager::Mesh2D& newMesh,
515 Vector< Extent >& extents,
518 float underlinePosition,
519 float underlineThickness,
520 AtlasManager::AtlasSlot& slot )
524 float left = newMesh.mVertices[ 0 ].mPosition.x;
525 float right = newMesh.mVertices[ 1 ].mPosition.x;
527 // Check to see if there's a mesh data object that references the same atlas ?
529 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
530 mEndIt = meshContainer.end();
534 if( slot.mAtlasId == mIt->mAtlasId )
536 // Append the mesh to the existing mesh and adjust any extents
537 Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
541 AdjustExtents( extents,
548 underlineThickness );
555 // No mesh data object currently exists that references this atlas, so create a new one
556 MeshRecord meshRecord;
557 meshRecord.mAtlasId = slot.mAtlasId;
558 meshRecord.mMesh = newMesh;
559 meshContainer.push_back( meshRecord );
563 // Adjust extents for this new meshrecord
564 AdjustExtents( extents,
566 meshContainer.size() - 1u,
571 underlineThickness );
576 void AdjustExtents( Vector< Extent >& extents,
577 std::vector< MeshRecord>& meshRecords,
582 float underlinePosition,
583 float underlineThickness )
585 bool foundExtent = false;
586 for ( Vector< Extent >::Iterator eIt = extents.Begin(),
587 eEndIt = extents.End();
591 if ( Equals( baseLine, eIt->mBaseLine ) )
594 if ( left < eIt->mLeft )
598 if ( right > eIt->mRight )
603 if ( underlinePosition > eIt->mUnderlinePosition )
605 eIt->mUnderlinePosition = underlinePosition;
607 if ( underlineThickness > eIt->mUnderlineThickness )
609 eIt->mUnderlineThickness = underlineThickness;
617 extent.mRight = right;
618 extent.mBaseLine = baseLine;
619 extent.mUnderlinePosition = underlinePosition;
620 extent.mUnderlineThickness = underlineThickness;
621 extent.mMeshRecordIndex = index;
622 extents.PushBack( extent );
626 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
628 for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
629 glyphEndIt = glyphs.End();
630 glyphIt != glyphEndIt;
633 const FontId fontId = (*glyphIt).fontId;
634 bool foundFont = false;
636 for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
637 blockEndIt = mBlockSizes.end();
638 blockIt != blockEndIt;
641 if( (*blockIt).mFontId == fontId )
650 FontMetrics fontMetrics;
651 mFontClient.GetFontMetrics( fontId, fontMetrics );
653 MaxBlockSize maxBlockSize;
654 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
655 maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
656 maxBlockSize.mFontId = fontId;
658 mBlockSizes.push_back( maxBlockSize );
663 void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
664 Vector< Extent >& extents,
665 const Vector4& underlineColor )
667 AtlasManager::Mesh2D newMesh;
668 unsigned short faceIndex = 0;
669 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
670 eEndIt = extents.End();
674 AtlasManager::Vertex2D vert;
675 uint32_t index = eIt->mMeshRecordIndex;
676 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
678 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
679 float u = HALF / uv.x;
680 float v = HALF / uv.y;
681 float thickness = eIt->mUnderlineThickness;
682 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
683 float tlx = eIt->mLeft;
684 float brx = eIt->mRight;
686 vert.mPosition.x = tlx;
687 vert.mPosition.y = baseLine;
688 vert.mTexCoords.x = ZERO;
689 vert.mTexCoords.y = ZERO;
690 newMesh.mVertices.PushBack( vert );
692 vert.mPosition.x = brx;
693 vert.mPosition.y = baseLine;
694 vert.mTexCoords.x = u;
695 newMesh.mVertices.PushBack( vert );
697 vert.mPosition.x = tlx;
698 vert.mPosition.y = baseLine + thickness;
699 vert.mTexCoords.x = ZERO;
700 vert.mTexCoords.y = v;
701 newMesh.mVertices.PushBack( vert );
703 vert.mPosition.x = brx;
704 vert.mPosition.y = baseLine + thickness;
705 vert.mTexCoords.x = u;
706 newMesh.mVertices.PushBack( vert );
708 // Six indices in counter clockwise winding
709 newMesh.mIndices.PushBack( faceIndex + 1u );
710 newMesh.mIndices.PushBack( faceIndex );
711 newMesh.mIndices.PushBack( faceIndex + 2u );
712 newMesh.mIndices.PushBack( faceIndex + 2u );
713 newMesh.mIndices.PushBack( faceIndex + 3u );
714 newMesh.mIndices.PushBack( faceIndex + 1u );
717 vert.mColor = underlineColor;
719 Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
723 Actor mActor; ///< The actor parent which renders the text
724 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
725 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
726 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
727 Vector< TextCacheEntry > mTextCache; ///> Caches data from previous render
728 Property::Map mQuadVertexFormat; ///> Describes the vertex 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 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
758 glyphs.Resize( numberOfGlyphs );
759 positions.Resize( numberOfGlyphs );
761 const Vector4* const colorsBuffer = view.GetColors();
762 const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
763 const Vector4& defaultColor = view.GetTextColor();
765 mImpl->AddGlyphs( view,
773 /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
774 /* 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. */
775 if ( !mImpl->mActor )
777 mImpl->mActor = Actor::New();
781 return mImpl->mActor;
784 AtlasRenderer::AtlasRenderer()
790 AtlasRenderer::~AtlasRenderer()