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 Text::GlyphIndex mIndex;
92 uint32_t mNeededBlockWidth;
93 uint32_t mNeededBlockHeight;
98 mGlyphManager = AtlasGlyphManager::Get();
99 mFontClient = TextAbstraction::FontClient::Get();
100 mBasicShader = BasicShader::New();
101 mBgraShader = BgraShader::New();
102 mBasicShadowShader = BasicShadowShader::New();
105 mFace.push_back( 0 ); mFace.push_back( 2u ); mFace.push_back( 1u );
106 mFace.push_back( 1u ); mFace.push_back( 2u ); mFace.push_back( 3u );
109 void AddGlyphs( const std::vector<Vector2>& positions,
110 const Vector<GlyphInfo>& glyphs,
111 const Vector4& textColor,
112 const Vector2& shadowOffset,
113 const Vector4& shadowColor,
114 bool underlineEnabled,
115 const Vector4& underlineColor,
116 float underlineHeight )
118 AtlasManager::AtlasSlot slot;
119 std::vector< MeshRecord > meshContainer;
120 Vector< Extent > extents;
122 float currentUnderlinePosition = ZERO;
123 float currentUnderlineThickness = underlineHeight;
124 uint32_t currentBlockSize = 0;
125 FontId lastFontId = 0;
126 Style style = STYLE_NORMAL;
128 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
130 style = STYLE_DROP_SHADOW;
133 if ( mImageIds.Size() )
135 // Unreference any currently used glyphs
139 CalculateBlocksSize( glyphs );
141 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
143 const GlyphInfo& glyph = glyphs[ i ];
145 // No operation for white space
146 if ( glyph.width && glyph.height )
148 // Are we still using the same fontId as previous
149 if ( glyph.fontId != lastFontId )
151 // We need to fetch fresh font underline metrics
152 FontMetrics fontMetrics;
153 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
154 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
155 float descender = ceil( fabsf( fontMetrics.descender ) );
157 if ( underlineHeight == ZERO )
159 currentUnderlineThickness = fontMetrics.underlineThickness;
161 // Ensure underline will be at least a pixel high
162 if ( currentUnderlineThickness < ONE )
164 currentUnderlineThickness = ONE;
168 currentUnderlineThickness = ceil( currentUnderlineThickness );
172 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
173 if ( currentUnderlinePosition > descender )
175 currentUnderlinePosition = descender;
177 if ( ZERO == currentUnderlinePosition )
179 // Move offset down by one ( EFL behavior )
180 currentUnderlinePosition = ONE;
184 const Vector2& position = positions[ i ];
185 MeshData newMeshData;
186 mGlyphManager.Cached( glyph.fontId, glyph.index, slot );
190 // This glyph already exists so generate mesh data plugging in our supplied position
191 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMeshData );
192 mImageIds.PushBack( slot.mImageId );
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, bitmap, slot );
241 // Generate mesh data for this quad, plugging in our supplied position
244 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMeshData );
245 mImageIds.PushBack( slot.mImageId );
249 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
250 StitchTextMesh( meshContainer,
254 position.y + glyph.yBearing,
255 currentUnderlinePosition,
256 currentUnderlineThickness,
258 lastFontId = glyph.fontId;
262 if ( underlineEnabled )
264 // Check to see if any of the text needs an underline
265 GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
268 // For each MeshData object, create a mesh actor and add to the renderable actor
269 if ( meshContainer.size() )
271 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt )
273 MeshActor actor = MeshActor::New( Mesh::New( mIt->mMeshData ) );
274 actor.SetColor( mIt->mColor );
276 // Ensure that text rendering is unfiltered
277 actor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
278 if ( mIt->mIsUnderline )
280 actor.SetColorMode( USE_OWN_COLOR );
284 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
287 // Check to see what pixel format the shader should be
288 if ( mGlyphManager.GetPixelFormat( mIt->mAtlasId ) == Pixel::L8 )
290 // Create an effect if necessary
291 if ( style == STYLE_DROP_SHADOW )
293 actor.Add( GenerateShadow( *mIt, shadowOffset, shadowColor ) );
295 actor.SetShaderEffect( mBasicShader );
299 actor.SetShaderEffect( mBgraShader );
311 mActor.OffStageSignal().Connect( this, &AtlasRenderer::Impl::OffStageDisconnect );
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 // Unreference any glyphs that were used with this actor
438 void OffStageDisconnect( Dali::Actor actor )
445 for ( uint32_t i = 0; i < mImageIds.Size(); ++i )
447 mGlyphManager.Remove( mImageIds[ i ] );
449 mImageIds.Resize( 0 );
452 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
454 MaxBlockSize maxBlockSize;
455 for ( uint32_t i = 0; i < glyphs.Size(); ++i )
457 FontId fontId = glyphs[ i ].fontId;
458 bool foundFont = false;
459 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
461 if ( mBlockSizes[ j ].mFontId == fontId )
468 FontMetrics fontMetrics;
469 mFontClient.GetFontMetrics( fontId, fontMetrics );
470 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
471 maxBlockSize.mNeededBlockHeight = static_cast< uint32_t >( fontMetrics.height );
472 maxBlockSize.mFontId = fontId;
473 mBlockSizes.push_back( maxBlockSize );
478 void GenerateUnderlines( std::vector< MeshRecord>& meshRecords,
479 Vector< Extent >& extents,
480 const Vector4& underlineColor,
481 const Vector4& textColor )
483 MeshData newMeshData;
484 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(); eIt != extents.End(); ++eIt )
486 MeshData::VertexContainer newVerts;
487 newVerts.reserve( 4u );
488 uint32_t index = eIt->mMeshRecordIndex;
489 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
491 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
492 float u = HALF / uv.x;
493 float v = HALF / uv.y;
494 float thickness = eIt->mUnderlineThickness;
495 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
496 float tlx = eIt->mLeft;
497 float brx = eIt->mRight;
499 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine, ZERO ),
503 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine, ZERO ),
507 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine + thickness, ZERO ),
511 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine + thickness, ZERO ),
515 newMeshData.SetVertices( newVerts );
516 newMeshData.SetFaceIndices( mFace );
518 if ( underlineColor == textColor )
520 mGlyphManager.StitchMesh( meshRecords[ index ].mMeshData, newMeshData );
525 newMeshData.SetMaterial( meshRecords[ index ].mMeshData.GetMaterial() );
526 newMeshData.SetHasNormals( true );
527 newMeshData.SetHasColor( false );
528 newMeshData.SetHasTextureCoords( true );
529 record.mMeshData = newMeshData;
530 record.mAtlasId = meshRecords[ index ].mAtlasId;
531 record.mColor = underlineColor;
532 record.mIsUnderline = true;
533 meshRecords.push_back( record );
538 MeshActor GenerateShadow( MeshRecord& meshRecord,
539 const Vector2& shadowOffset,
540 const Vector4& shadowColor )
542 // Scan vertex buffer to determine width and height of effect buffer needed
543 MeshData::VertexContainer verts = meshRecord.mMeshData.GetVertices();
544 float tlx = verts[ 0 ].x;
545 float tly = verts[ 0 ].y;
549 for ( uint32_t i = 0; i < verts.size(); ++i )
551 if ( verts[ i ].x < tlx )
555 if ( verts[ i ].y < tly )
559 if ( verts[ i ].x > brx )
563 if ( verts[ i ].y > bry )
569 float width = brx - tlx;
570 float height = bry - tly;
571 float divWidth = TWO / width;
572 float divHeight = TWO / height;
574 // Create a buffer to render to
575 meshRecord.mBuffer = FrameBufferImage::New( width, height );
577 // Create a mesh actor to contain the post-effect render
578 MeshData::VertexContainer vertices;
579 MeshData::FaceIndices face;
581 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
585 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
586 Vector2( ONE, ZERO ),
589 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
590 Vector2( ZERO, ONE ),
593 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
598 Material newMaterial = Material::New("effect buffer");
599 newMaterial.SetDiffuseTexture( meshRecord.mBuffer );
600 meshData.SetMaterial( newMaterial );
601 meshData.SetVertices( vertices );
602 meshData.SetFaceIndices( mFace );
603 meshData.SetHasNormals( true );
604 meshData.SetHasColor( false );
605 meshData.SetHasTextureCoords( true );
606 MeshActor actor = MeshActor::New( Mesh::New( meshData ) );
607 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
608 actor.SetShaderEffect( mBgraShader );
609 actor.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
610 actor.SetSortModifier( 0.1f ); // force behind main text
612 // Create a sub actor to render once with normalized vertex positions
613 MeshData newMeshData;
614 MeshData::VertexContainer newVerts;
615 MeshData::FaceIndices newFaces;
616 MeshData::FaceIndices faces = meshRecord.mMeshData.GetFaces();
617 for ( uint32_t i = 0; i < verts.size(); ++i )
619 MeshData::Vertex vertex = verts[ i ];
620 vertex.x = ( ( vertex.x - tlx ) * divWidth ) - ONE;
621 vertex.y = ( ( vertex.y - tly ) * divHeight ) - ONE;
622 newVerts.push_back( vertex );
625 // Reverse triangle winding order
626 uint32_t faceCount = faces.size() / 3;
627 for ( uint32_t i = 0; i < faceCount; ++i )
629 uint32_t index = i * 3;
630 newFaces.push_back( faces[ index + 2 ] );
631 newFaces.push_back( faces[ index + 1 ] );
632 newFaces.push_back( faces[ index ] );
635 newMeshData.SetMaterial( meshRecord.mMeshData.GetMaterial() );
636 newMeshData.SetVertices( newVerts );
637 newMeshData.SetFaceIndices( newFaces );
638 newMeshData.SetHasNormals( true );
639 newMeshData.SetHasColor( false );
640 newMeshData.SetHasTextureCoords( true );
642 MeshActor subActor = MeshActor::New( Mesh::New( newMeshData ) );
643 subActor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
644 subActor.SetColor( shadowColor );
645 subActor.SetShaderEffect( mBasicShadowShader );
646 subActor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
648 // Create a render task to render the effect
649 RenderTask task = Stage::GetCurrent().GetRenderTaskList().CreateTask();
650 task.SetTargetFrameBuffer( meshRecord.mBuffer );
651 task.SetSourceActor( subActor );
652 task.SetClearEnabled( true );
653 task.SetClearColor( Vector4::ZERO );
654 task.SetExclusive( true );
655 task.SetRefreshRate( RenderTask::REFRESH_ONCE );
656 task.FinishedSignal().Connect( this, &AtlasRenderer::Impl::RenderComplete );
657 actor.Add( subActor );
661 void RenderComplete( RenderTask& renderTask )
663 // Disconnect and remove this single shot render task
664 renderTask.FinishedSignal().Disconnect( this, &AtlasRenderer::Impl::RenderComplete );
665 Stage::GetCurrent().GetRenderTaskList().RemoveTask( renderTask );
667 // Get the actor used for render to buffer and remove it from the parent
668 Actor renderActor = renderTask.GetSourceActor();
671 Actor parent = renderActor.GetParent();
674 parent.Remove( renderActor );
679 RenderableActor mActor; ///< The actor parent which renders the text
680 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
681 Vector< uint32_t > mImageIds; ///< A list of imageIDs used by the renderer
682 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
683 ShaderEffect mBasicShader; ///> Shader used to render L8 glyphs
684 ShaderEffect mBgraShader; ///> Shader used to render BGRA glyphs
685 ShaderEffect mBasicShadowShader; ///> Shader used to render drop shadow into buffer
686 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
687 std::vector< MeshData::FaceIndex > mFace; ///> Face indices for a quad
690 Text::RendererPtr AtlasRenderer::New()
692 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
694 return Text::RendererPtr( new AtlasRenderer() );
697 RenderableActor AtlasRenderer::Render( Text::ViewInterface& view )
699 UnparentAndReset( mImpl->mActor );
701 Length numberOfGlyphs = view.GetNumberOfGlyphs();
703 if( numberOfGlyphs > 0u )
705 Vector<GlyphInfo> glyphs;
706 glyphs.Resize( numberOfGlyphs );
708 std::vector<Vector2> positions;
709 positions.resize( numberOfGlyphs );
711 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
715 glyphs.Resize( numberOfGlyphs );
716 positions.resize( numberOfGlyphs );
718 mImpl->AddGlyphs( positions,
721 view.GetShadowOffset(),
722 view.GetShadowColor(),
723 view.IsUnderlineEnabled(),
724 view.GetUnderlineColor(),
725 view.GetUnderlineHeight() );
728 return mImpl->mActor;
731 AtlasRenderer::AtlasRenderer()
737 AtlasRenderer::~AtlasRenderer()