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/dali.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/devel-api/text-abstraction/font-client.h>
25 #include <dali/devel-api/actors/mesh-actor.h>
26 #include <dali/devel-api/geometry/mesh.h>
30 #include <dali-toolkit/internal/atlas-manager/atlas-manager.h>
31 #include <dali-toolkit/internal/text/line-run.h>
32 #include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
33 #include <dali-toolkit/internal/text/rendering/shaders/text-basic-shader.h>
34 #include <dali-toolkit/internal/text/rendering/shaders/text-bgra-shader.h>
35 #include <dali-toolkit/internal/text/rendering/shaders/text-basic-shadow-shader.h>
38 using namespace Dali::Toolkit;
39 using namespace Dali::Toolkit::Text;
43 #if defined(DEBUG_ENABLED)
44 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
47 const float ZERO( 0.0f );
48 const float HALF( 0.5f );
49 const float ONE( 1.0f );
50 const float TWO( 2.0f );
51 const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
52 const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
55 struct AtlasRenderer::Impl : public ConnectionTracker
69 FrameBufferImage mBuffer;
78 float mUnderlinePosition;
79 float mUnderlineThickness;
80 uint32_t mMeshRecordIndex;
86 uint32_t mNeededBlockWidth;
87 uint32_t mNeededBlockHeight;
93 Text::GlyphIndex mIndex;
99 Text::GlyphIndex mIndex;
105 mGlyphManager = AtlasGlyphManager::Get();
106 mFontClient = TextAbstraction::FontClient::Get();
107 mBasicShader = BasicShader::New();
108 mBgraShader = BgraShader::New();
109 mBasicShadowShader = BasicShadowShader::New();
112 mFace.push_back( 0 ); mFace.push_back( 2u ); mFace.push_back( 1u );
113 mFace.push_back( 1u ); mFace.push_back( 2u ); mFace.push_back( 3u );
116 void AddGlyphs( const std::vector<Vector2>& positions,
117 const Vector<GlyphInfo>& glyphs,
118 const Vector4& textColor,
119 const Vector2& shadowOffset,
120 const Vector4& shadowColor,
121 bool underlineEnabled,
122 const Vector4& underlineColor,
123 float underlineHeight )
125 AtlasManager::AtlasSlot slot;
126 std::vector< MeshRecord > meshContainer;
127 Vector< Extent > extents;
128 TextCacheEntry textCacheEntry;
130 float currentUnderlinePosition = ZERO;
131 float currentUnderlineThickness = underlineHeight;
132 uint32_t currentBlockSize = 0;
133 FontId lastFontId = 0;
134 Style style = STYLE_NORMAL;
136 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
138 style = STYLE_DROP_SHADOW;
141 if ( mTextCache.Size() )
143 // Update the glyph cache with any changes to current text
144 RemoveText( glyphs );
147 CalculateBlocksSize( glyphs );
149 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
151 const GlyphInfo& glyph = glyphs[ i ];
153 // No operation for white space
154 if ( glyph.width && glyph.height )
156 // Are we still using the same fontId as previous
157 if ( glyph.fontId != lastFontId )
159 // We need to fetch fresh font underline metrics
160 FontMetrics fontMetrics;
161 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
162 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
163 float descender = ceil( fabsf( fontMetrics.descender ) );
165 if ( underlineHeight == ZERO )
167 currentUnderlineThickness = fontMetrics.underlineThickness;
169 // Ensure underline will be at least a pixel high
170 if ( currentUnderlineThickness < ONE )
172 currentUnderlineThickness = ONE;
176 currentUnderlineThickness = ceil( currentUnderlineThickness );
180 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
181 if ( currentUnderlinePosition > descender )
183 currentUnderlinePosition = descender;
185 if ( ZERO == currentUnderlinePosition )
187 // Move offset down by one ( EFL behavior )
188 currentUnderlinePosition = ONE;
192 const Vector2& position = positions[ i ];
193 MeshData newMeshData;
195 if ( !mGlyphManager.Cached( glyph.fontId, glyph.index, slot ) )
197 // Select correct size for new atlas if needed....?
198 if ( lastFontId != glyph.fontId )
200 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
202 if ( mBlockSizes[ j ].mFontId == glyph.fontId )
204 currentBlockSize = j;
205 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
206 DEFAULT_ATLAS_HEIGHT,
207 mBlockSizes[ j ].mNeededBlockWidth,
208 mBlockSizes[ j ].mNeededBlockHeight );
213 // Create a new image for the glyph
214 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
217 // Ensure that the next image will fit into the current block size
218 bool setSize = false;
219 if ( bitmap.GetWidth() > mBlockSizes[ currentBlockSize ].mNeededBlockWidth )
222 mBlockSizes[ currentBlockSize ].mNeededBlockWidth = bitmap.GetWidth();
224 if ( bitmap.GetHeight() > mBlockSizes[ currentBlockSize ].mNeededBlockHeight )
227 mBlockSizes[ currentBlockSize ].mNeededBlockHeight = bitmap.GetHeight();
232 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
233 DEFAULT_ATLAS_HEIGHT,
234 mBlockSizes[ currentBlockSize ].mNeededBlockWidth,
235 mBlockSizes[ currentBlockSize ].mNeededBlockHeight );
238 // Locate a new slot for our glyph
239 mGlyphManager.Add( glyph.fontId, glyph, bitmap, slot );
243 // Generate mesh data for this quad, plugging in our supplied position
244 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMeshData );
245 textCacheEntry.mFontId = glyph.fontId;
246 textCacheEntry.mImageId = slot.mImageId;
247 textCacheEntry.mIndex = glyph.index;
248 mTextCache.PushBack( textCacheEntry );
250 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
251 StitchTextMesh( meshContainer,
255 position.y + glyph.yBearing,
256 currentUnderlinePosition,
257 currentUnderlineThickness,
259 lastFontId = glyph.fontId;
263 if ( underlineEnabled )
265 // Check to see if any of the text needs an underline
266 GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
269 // For each MeshData object, create a mesh actor and add to the renderable actor
270 if ( meshContainer.size() )
272 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt )
274 MeshActor actor = MeshActor::New( Mesh::New( mIt->mMeshData ) );
275 actor.SetColor( mIt->mColor );
277 // Ensure that text rendering is unfiltered
278 actor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
279 if ( mIt->mIsUnderline )
281 actor.SetColorMode( USE_OWN_COLOR );
285 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
288 // Check to see what pixel format the shader should be
289 if ( mGlyphManager.GetPixelFormat( mIt->mAtlasId ) == Pixel::L8 )
291 // Create an effect if necessary
292 if ( style == STYLE_DROP_SHADOW )
294 actor.Add( GenerateShadow( *mIt, shadowOffset, shadowColor ) );
296 actor.SetShaderEffect( mBasicShader );
300 actor.SetShaderEffect( mBgraShader );
313 #if defined(DEBUG_ENABLED)
314 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
315 DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
317 metrics.mAtlasMetrics.mAtlasCount,
318 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
319 for ( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
321 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
322 i + 1, i > 8 ? "" : " ",
323 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
324 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
325 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
326 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
327 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
328 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
329 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
334 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
335 MeshData& newMeshData,
336 Vector< Extent >& extents,
337 const Vector4& color,
339 float underlinePosition,
340 float underlineThickness,
341 AtlasManager::AtlasSlot& slot )
345 MeshData::VertexContainer verts = newMeshData.GetVertices();
346 float left = verts[ 0 ].x;
347 float right = verts[ 1 ].x;
349 // Check to see if there's a mesh data object that references the same atlas ?
351 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt, ++index )
353 if ( slot.mAtlasId == mIt->mAtlasId && color == mIt->mColor )
355 // Stitch the mesh to the existing mesh and adjust any extents
356 mGlyphManager.StitchMesh( mIt->mMeshData, newMeshData );
357 AdjustExtents( extents,
364 underlineThickness );
369 // No mesh data object currently exists that references this atlas, so create a new one
370 MeshRecord meshRecord;
371 meshRecord.mAtlasId = slot.mAtlasId;
372 meshRecord.mMeshData = newMeshData;
373 meshRecord.mColor = color;
374 meshRecord.mIsUnderline = false;
375 meshContainer.push_back( meshRecord );
377 // Adjust extents for this new meshrecord
378 AdjustExtents( extents,
380 meshContainer.size() - 1u,
385 underlineThickness );
390 void AdjustExtents( Vector< Extent >& extents,
391 std::vector< MeshRecord>& meshRecords,
396 float underlinePosition,
397 float underlineThickness )
399 bool foundExtent = false;
400 for ( Vector< Extent >::Iterator eIt = extents.Begin(); eIt != extents.End(); ++eIt )
402 if ( Equals( baseLine, eIt->mBaseLine ) )
405 if ( left < eIt->mLeft )
409 if ( right > eIt->mRight )
414 if ( underlinePosition > eIt->mUnderlinePosition )
416 eIt->mUnderlinePosition = underlinePosition;
418 if ( underlineThickness > eIt->mUnderlineThickness )
420 eIt->mUnderlineThickness = underlineThickness;
428 extent.mRight = right;
429 extent.mBaseLine = baseLine;
430 extent.mUnderlinePosition = underlinePosition;
431 extent.mUnderlineThickness = underlineThickness;
432 extent.mMeshRecordIndex = index;
433 extents.PushBack( extent );
437 void RemoveText( const Vector<GlyphInfo>& glyphs )
439 Vector< CheckEntry > checked;
440 CheckEntry checkEntry;
442 for ( Vector< TextCacheEntry >::Iterator tCit = mTextCache.Begin(); tCit != mTextCache.End(); ++tCit )
444 uint32_t index = tCit->mIndex;
445 uint32_t fontId = tCit->mFontId;
447 // Check that this character has not already been checked...
448 bool wasChecked = false;
449 for ( Vector< CheckEntry >::Iterator cEit = checked.Begin(); cEit != checked.End(); ++cEit )
451 if ( fontId == cEit->mFontId && index == cEit->mIndex )
460 int32_t newCount = 0;
461 int32_t oldCount = 0;
463 // How many times does this character occur in the old text ?
464 for ( Vector< TextCacheEntry >::Iterator oTcit = mTextCache.Begin(); oTcit != mTextCache.End(); ++oTcit )
466 if ( fontId == oTcit->mFontId && index == oTcit->mIndex )
472 // And how many times in the new ?
473 for ( Vector< GlyphInfo >::Iterator cGit = glyphs.Begin(); cGit != glyphs.End(); ++cGit )
475 if ( fontId == cGit->fontId && index == cGit->index )
480 mGlyphManager.AdjustReferenceCount( fontId, tCit->mImageId, newCount - oldCount );
481 checkEntry.mIndex = index;
482 checkEntry.mFontId = fontId;
483 checked.PushBack( checkEntry );
486 mTextCache.Resize( 0 );
489 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
491 MaxBlockSize maxBlockSize;
492 for ( uint32_t i = 0; i < glyphs.Size(); ++i )
494 FontId fontId = glyphs[ i ].fontId;
495 bool foundFont = false;
496 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
498 if ( mBlockSizes[ j ].mFontId == fontId )
505 FontMetrics fontMetrics;
506 mFontClient.GetFontMetrics( fontId, fontMetrics );
507 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
508 maxBlockSize.mNeededBlockHeight = static_cast< uint32_t >( fontMetrics.height );
509 maxBlockSize.mFontId = fontId;
510 mBlockSizes.push_back( maxBlockSize );
515 void GenerateUnderlines( std::vector< MeshRecord>& meshRecords,
516 Vector< Extent >& extents,
517 const Vector4& underlineColor,
518 const Vector4& textColor )
520 MeshData newMeshData;
521 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(); eIt != extents.End(); ++eIt )
523 MeshData::VertexContainer newVerts;
524 newVerts.reserve( 4u );
525 uint32_t index = eIt->mMeshRecordIndex;
526 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
528 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
529 float u = HALF / uv.x;
530 float v = HALF / uv.y;
531 float thickness = eIt->mUnderlineThickness;
532 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
533 float tlx = eIt->mLeft;
534 float brx = eIt->mRight;
536 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine, ZERO ),
540 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine, ZERO ),
544 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine + thickness, ZERO ),
548 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine + thickness, ZERO ),
552 newMeshData.SetVertices( newVerts );
553 newMeshData.SetFaceIndices( mFace );
555 if ( underlineColor == textColor )
557 mGlyphManager.StitchMesh( meshRecords[ index ].mMeshData, newMeshData );
562 newMeshData.SetMaterial( meshRecords[ index ].mMeshData.GetMaterial() );
563 newMeshData.SetHasNormals( true );
564 newMeshData.SetHasColor( false );
565 newMeshData.SetHasTextureCoords( true );
566 record.mMeshData = newMeshData;
567 record.mAtlasId = meshRecords[ index ].mAtlasId;
568 record.mColor = underlineColor;
569 record.mIsUnderline = true;
570 meshRecords.push_back( record );
575 MeshActor GenerateShadow( MeshRecord& meshRecord,
576 const Vector2& shadowOffset,
577 const Vector4& shadowColor )
579 // Scan vertex buffer to determine width and height of effect buffer needed
580 MeshData::VertexContainer verts = meshRecord.mMeshData.GetVertices();
581 float tlx = verts[ 0 ].x;
582 float tly = verts[ 0 ].y;
586 for ( uint32_t i = 0; i < verts.size(); ++i )
588 if ( verts[ i ].x < tlx )
592 if ( verts[ i ].y < tly )
596 if ( verts[ i ].x > brx )
600 if ( verts[ i ].y > bry )
606 float width = brx - tlx;
607 float height = bry - tly;
608 float divWidth = TWO / width;
609 float divHeight = TWO / height;
611 // Create a buffer to render to
612 meshRecord.mBuffer = FrameBufferImage::New( width, height );
614 // Create a mesh actor to contain the post-effect render
615 MeshData::VertexContainer vertices;
616 MeshData::FaceIndices face;
618 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
622 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
623 Vector2( ONE, ZERO ),
626 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
627 Vector2( ZERO, ONE ),
630 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
635 Material newMaterial = Material::New("effect buffer");
636 newMaterial.SetDiffuseTexture( meshRecord.mBuffer );
637 meshData.SetMaterial( newMaterial );
638 meshData.SetVertices( vertices );
639 meshData.SetFaceIndices( mFace );
640 meshData.SetHasNormals( true );
641 meshData.SetHasColor( false );
642 meshData.SetHasTextureCoords( true );
643 MeshActor actor = MeshActor::New( Mesh::New( meshData ) );
644 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
645 actor.SetShaderEffect( mBgraShader );
646 actor.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
647 actor.SetSortModifier( 0.1f ); // force behind main text
649 // Create a sub actor to render once with normalized vertex positions
650 MeshData newMeshData;
651 MeshData::VertexContainer newVerts;
652 MeshData::FaceIndices newFaces;
653 MeshData::FaceIndices faces = meshRecord.mMeshData.GetFaces();
654 for ( uint32_t i = 0; i < verts.size(); ++i )
656 MeshData::Vertex vertex = verts[ i ];
657 vertex.x = ( ( vertex.x - tlx ) * divWidth ) - ONE;
658 vertex.y = ( ( vertex.y - tly ) * divHeight ) - ONE;
659 newVerts.push_back( vertex );
662 // Reverse triangle winding order
663 uint32_t faceCount = faces.size() / 3;
664 for ( uint32_t i = 0; i < faceCount; ++i )
666 uint32_t index = i * 3;
667 newFaces.push_back( faces[ index + 2 ] );
668 newFaces.push_back( faces[ index + 1 ] );
669 newFaces.push_back( faces[ index ] );
672 newMeshData.SetMaterial( meshRecord.mMeshData.GetMaterial() );
673 newMeshData.SetVertices( newVerts );
674 newMeshData.SetFaceIndices( newFaces );
675 newMeshData.SetHasNormals( true );
676 newMeshData.SetHasColor( false );
677 newMeshData.SetHasTextureCoords( true );
679 MeshActor subActor = MeshActor::New( Mesh::New( newMeshData ) );
680 subActor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
681 subActor.SetColor( shadowColor );
682 subActor.SetShaderEffect( mBasicShadowShader );
683 subActor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
685 // Create a render task to render the effect
686 RenderTask task = Stage::GetCurrent().GetRenderTaskList().CreateTask();
687 task.SetTargetFrameBuffer( meshRecord.mBuffer );
688 task.SetSourceActor( subActor );
689 task.SetClearEnabled( true );
690 task.SetClearColor( Vector4::ZERO );
691 task.SetExclusive( true );
692 task.SetRefreshRate( RenderTask::REFRESH_ONCE );
693 task.FinishedSignal().Connect( this, &AtlasRenderer::Impl::RenderComplete );
694 actor.Add( subActor );
698 void RenderComplete( RenderTask& renderTask )
700 // Disconnect and remove this single shot render task
701 renderTask.FinishedSignal().Disconnect( this, &AtlasRenderer::Impl::RenderComplete );
702 Stage::GetCurrent().GetRenderTaskList().RemoveTask( renderTask );
704 // Get the actor used for render to buffer and remove it from the parent
705 Actor renderActor = renderTask.GetSourceActor();
708 Actor parent = renderActor.GetParent();
711 parent.Remove( renderActor );
716 RenderableActor mActor; ///< The actor parent which renders the text
717 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
718 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
719 ShaderEffect mBasicShader; ///> Shader used to render L8 glyphs
720 ShaderEffect mBgraShader; ///> Shader used to render BGRA glyphs
721 ShaderEffect mBasicShadowShader; ///> Shader used to render drop shadow into buffer
722 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
723 std::vector< MeshData::FaceIndex > mFace; ///> Face indices for a quad
724 Vector< TextCacheEntry > mTextCache;
727 Text::RendererPtr AtlasRenderer::New()
729 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
731 return Text::RendererPtr( new AtlasRenderer() );
734 RenderableActor AtlasRenderer::Render( Text::ViewInterface& view )
736 UnparentAndReset( mImpl->mActor );
738 Length numberOfGlyphs = view.GetNumberOfGlyphs();
740 if( numberOfGlyphs > 0u )
742 Vector<GlyphInfo> glyphs;
743 glyphs.Resize( numberOfGlyphs );
745 std::vector<Vector2> positions;
746 positions.resize( numberOfGlyphs );
748 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
752 glyphs.Resize( numberOfGlyphs );
753 positions.resize( numberOfGlyphs );
755 mImpl->AddGlyphs( positions,
758 view.GetShadowOffset(),
759 view.GetShadowColor(),
760 view.IsUnderlineEnabled(),
761 view.GetUnderlineColor(),
762 view.GetUnderlineHeight() );
765 return mImpl->mActor;
768 AtlasRenderer::AtlasRenderer()
774 AtlasRenderer::~AtlasRenderer()
776 Vector< GlyphInfo > emptyGlyphs;
777 mImpl->RemoveText( emptyGlyphs );