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/public-api/text-abstraction/text-abstraction.h>
27 #include <dali-toolkit/internal/atlas-manager/atlas-manager.h>
28 #include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
29 #include <dali-toolkit/internal/text/rendering/shaders/text-basic-shader.h>
30 #include <dali-toolkit/internal/text/rendering/shaders/text-bgra-shader.h>
31 #include <dali-toolkit/internal/text/rendering/shaders/text-basic-shadow-shader.h>
32 #if defined(DEBUG_ENABLED)
33 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_ATLAS_RENDERER");
37 using namespace Dali::Toolkit;
38 using namespace Dali::Toolkit::Text;
42 const float ZERO( 0.0f );
43 const float HALF( 0.5f );
44 const float ONE( 1.0f );
45 const float TWO( 2.0f );
46 const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
47 const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
50 struct AtlasRenderer::Impl : public ConnectionTracker
64 FrameBufferImage mBuffer;
73 float mUnderlinePosition;
74 float mUnderlineThickness;
75 uint32_t mMeshRecordIndex;
81 Text::GlyphIndex mIndex;
87 uint32_t mNeededBlockWidth;
88 uint32_t mNeededBlockHeight;
93 mGlyphManager = AtlasGlyphManager::Get();
94 mFontClient = TextAbstraction::FontClient::Get();
95 mBasicShader = BasicShader::New();
96 mBgraShader = BgraShader::New();
97 mBasicShadowShader = BasicShadowShader::New();
100 mFace.push_back( 0 ); mFace.push_back( 2u ); mFace.push_back( 1u );
101 mFace.push_back( 1u ); mFace.push_back( 2u ); mFace.push_back( 3u );
104 void AddGlyphs( const std::vector<Vector2>& positions,
105 const Vector<GlyphInfo>& glyphs,
106 const Vector4& textColor,
107 const Vector2& shadowOffset,
108 const Vector4& shadowColor,
109 bool underlineEnabled,
110 const Vector4& underlineColor,
111 float underlineHeight )
113 AtlasManager::AtlasSlot slot;
114 std::vector< MeshRecord > meshContainer;
115 Vector< Extent > extents;
117 float currentUnderlinePosition = ZERO;
118 float currentUnderlineThickness = underlineHeight;
119 uint32_t currentBlockSize = 0;
120 FontId lastFontId = 0;
121 Style style = STYLE_NORMAL;
123 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
125 style = STYLE_DROP_SHADOW;
128 if ( mImageIds.Size() )
130 // Unreference any currently used glyphs
134 CalculateBlocksSize( glyphs );
136 for ( uint32_t i = 0; i < glyphs.Size(); ++i )
138 GlyphInfo glyph = glyphs[ i ];
140 // No operation for white space
141 if ( glyph.width && glyph.height )
143 // Are we still using the same fontId as previous
144 if ( glyph.fontId != lastFontId )
146 // We need to fetch fresh font underline metrics
147 FontMetrics fontMetrics;
148 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
149 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
150 float descender = ceil( fabsf( fontMetrics.descender ) );
152 if ( underlineHeight == ZERO )
154 currentUnderlineThickness = fontMetrics.underlineThickness;
156 // Ensure underline will be at least a pixel high
157 if ( currentUnderlineThickness < ONE )
159 currentUnderlineThickness = ONE;
163 currentUnderlineThickness = ceil( currentUnderlineThickness );
167 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
168 if ( currentUnderlinePosition > descender )
170 currentUnderlinePosition = descender;
172 if ( ZERO == currentUnderlinePosition )
174 // Move offset down by one ( EFL behavior )
175 currentUnderlinePosition = ONE;
179 Vector2 position = positions[ i ];
180 MeshData newMeshData;
181 mGlyphManager.Cached( glyph.fontId, glyph.index, slot );
185 // This glyph already exists so generate mesh data plugging in our supplied position
186 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMeshData );
187 mImageIds.PushBack( slot.mImageId );
192 // Select correct size for new atlas if needed....?
193 if ( lastFontId != glyph.fontId )
195 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
197 if ( mBlockSizes[ j ].mFontId == glyph.fontId )
199 currentBlockSize = j;
200 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
201 DEFAULT_ATLAS_HEIGHT,
202 mBlockSizes[ j ].mNeededBlockWidth,
203 mBlockSizes[ j ].mNeededBlockHeight );
208 // Create a new image for the glyph
209 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
212 // Ensure that the next image will fit into the current block size
213 bool setSize = false;
214 if ( bitmap.GetWidth() > mBlockSizes[ currentBlockSize ].mNeededBlockWidth )
217 mBlockSizes[ currentBlockSize ].mNeededBlockWidth = bitmap.GetWidth();
219 if ( bitmap.GetHeight() > mBlockSizes[ currentBlockSize ].mNeededBlockHeight )
222 mBlockSizes[ currentBlockSize ].mNeededBlockHeight = bitmap.GetHeight();
227 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
228 DEFAULT_ATLAS_HEIGHT,
229 mBlockSizes[ currentBlockSize ].mNeededBlockWidth,
230 mBlockSizes[ currentBlockSize ].mNeededBlockHeight );
233 // Locate a new slot for our glyph
234 mGlyphManager.Add( glyph, bitmap, slot );
236 // Generate mesh data for this quad, plugging in our supplied position
239 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMeshData );
240 mImageIds.PushBack( slot.mImageId );
244 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
245 StitchTextMesh( meshContainer,
249 position.y + glyph.yBearing,
250 currentUnderlinePosition,
251 currentUnderlineThickness,
253 lastFontId = glyph.fontId;
257 if ( underlineEnabled )
259 // Check to see if any of the text needs an underline
260 GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
263 // For each MeshData object, create a mesh actor and add to the renderable actor
264 if ( meshContainer.size() )
266 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt )
268 MeshActor actor = MeshActor::New( Mesh::New( mIt->mMeshData ) );
269 actor.SetColor( mIt->mColor );
271 // Ensure that text rendering is unfiltered
272 actor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
273 if ( mIt->mIsUnderline )
275 actor.SetColorMode( USE_OWN_COLOR );
279 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
282 // Check to see what pixel format the shader should be
283 if ( mGlyphManager.GetPixelFormat( mIt->mAtlasId ) == Pixel::L8 )
285 // Create an effect if necessary
286 if ( style == STYLE_DROP_SHADOW )
288 actor.Add( GenerateShadow( *mIt, shadowOffset, shadowColor ) );
290 actor.SetShaderEffect( mBasicShader );
294 actor.SetShaderEffect( mBgraShader );
306 mActor.OffStageSignal().Connect( this, &AtlasRenderer::Impl::OffStageDisconnect );
308 #if defined(DEBUG_ENABLED)
309 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
310 DALI_LOG_INFO( gLogFilter, Debug::Concise, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
312 metrics.mAtlasMetrics.mAtlasCount,
313 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
314 for ( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
316 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
317 i + 1, i > 8 ? "" : " ",
318 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
319 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
320 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
321 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
322 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
323 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
324 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
329 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
330 MeshData& newMeshData,
331 Vector< Extent >& extents,
332 const Vector4& color,
334 float underlinePosition,
335 float underlineThickness,
336 AtlasManager::AtlasSlot& slot )
340 MeshData::VertexContainer verts = newMeshData.GetVertices();
341 float left = verts[ 0 ].x;
342 float right = verts[ 1 ].x;
344 // Check to see if there's a mesh data object that references the same atlas ?
346 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt, ++index )
348 if ( slot.mAtlasId == mIt->mAtlasId && color == mIt->mColor )
350 // Stitch the mesh to the existing mesh and adjust any extents
351 mGlyphManager.StitchMesh( mIt->mMeshData, newMeshData );
352 AdjustExtents( extents,
359 underlineThickness );
364 // No mesh data object currently exists that references this atlas, so create a new one
365 MeshRecord meshRecord;
366 meshRecord.mAtlasId = slot.mAtlasId;
367 meshRecord.mMeshData = newMeshData;
368 meshRecord.mColor = color;
369 meshRecord.mIsUnderline = false;
370 meshContainer.push_back( meshRecord );
372 // Adjust extents for this new meshrecord
373 AdjustExtents( extents,
375 meshContainer.size() - 1u,
380 underlineThickness );
385 void AdjustExtents( Vector< Extent >& extents,
386 std::vector< MeshRecord>& meshRecords,
391 float underlinePosition,
392 float underlineThickness )
394 bool foundExtent = false;
395 for ( Vector< Extent >::Iterator eIt = extents.Begin(); eIt != extents.End(); ++eIt )
397 if ( Equals( baseLine, eIt->mBaseLine ) )
400 if ( left < eIt->mLeft )
404 if ( right > eIt->mRight )
409 if ( underlinePosition > eIt->mUnderlinePosition )
411 eIt->mUnderlinePosition = underlinePosition;
413 if ( underlineThickness > eIt->mUnderlineThickness )
415 eIt->mUnderlineThickness = underlineThickness;
423 extent.mRight = right;
424 extent.mBaseLine = baseLine;
425 extent.mUnderlinePosition = underlinePosition;
426 extent.mUnderlineThickness = underlineThickness;
427 extent.mMeshRecordIndex = index;
428 extents.PushBack( extent );
432 // Unreference any glyphs that were used with this actor
433 void OffStageDisconnect( Dali::Actor actor )
440 for ( uint32_t i = 0; i < mImageIds.Size(); ++i )
442 mGlyphManager.Remove( mImageIds[ i ] );
444 mImageIds.Resize( 0 );
447 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
449 MaxBlockSize maxBlockSize;
450 for ( uint32_t i = 0; i < glyphs.Size(); ++i )
452 FontId fontId = glyphs[ i ].fontId;
453 bool foundFont = false;
454 for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
456 if ( mBlockSizes[ j ].mFontId == fontId )
463 FontMetrics fontMetrics;
464 mFontClient.GetFontMetrics( fontId, fontMetrics );
465 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
466 maxBlockSize.mNeededBlockHeight = static_cast< uint32_t >( fontMetrics.height );
467 maxBlockSize.mFontId = fontId;
468 mBlockSizes.push_back( maxBlockSize );
473 void GenerateUnderlines( std::vector< MeshRecord>& meshRecords,
474 Vector< Extent >& extents,
475 const Vector4& underlineColor,
476 const Vector4& textColor )
478 MeshData newMeshData;
479 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(); eIt != extents.End(); ++eIt )
481 MeshData::VertexContainer newVerts;
482 newVerts.reserve( 4u );
483 uint32_t index = eIt->mMeshRecordIndex;
484 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
486 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
487 float u = HALF / uv.x;
488 float v = HALF / uv.y;
489 float thickness = eIt->mUnderlineThickness;
490 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
491 float tlx = eIt->mLeft;
492 float brx = eIt->mRight;
494 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine, ZERO ),
498 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine, ZERO ),
502 newVerts.push_back( MeshData::Vertex( Vector3( tlx, baseLine + thickness, ZERO ),
506 newVerts.push_back( MeshData::Vertex( Vector3( brx, baseLine + thickness, ZERO ),
510 newMeshData.SetVertices( newVerts );
511 newMeshData.SetFaceIndices( mFace );
513 if ( underlineColor == textColor )
515 mGlyphManager.StitchMesh( meshRecords[ index ].mMeshData, newMeshData );
520 newMeshData.SetMaterial( meshRecords[ index ].mMeshData.GetMaterial() );
521 newMeshData.SetHasNormals( true );
522 newMeshData.SetHasColor( false );
523 newMeshData.SetHasTextureCoords( true );
524 record.mMeshData = newMeshData;
525 record.mAtlasId = meshRecords[ index ].mAtlasId;
526 record.mColor = underlineColor;
527 record.mIsUnderline = true;
528 meshRecords.push_back( record );
533 MeshActor GenerateShadow( MeshRecord& meshRecord,
534 const Vector2& shadowOffset,
535 const Vector4& shadowColor )
537 // Scan vertex buffer to determine width and height of effect buffer needed
538 MeshData::VertexContainer verts = meshRecord.mMeshData.GetVertices();
539 float tlx = verts[ 0 ].x;
540 float tly = verts[ 0 ].y;
544 for ( uint32_t i = 0; i < verts.size(); ++i )
546 if ( verts[ i ].x < tlx )
550 if ( verts[ i ].y < tly )
554 if ( verts[ i ].x > brx )
558 if ( verts[ i ].y > bry )
564 float width = brx - tlx;
565 float height = bry - tly;
566 float divWidth = TWO / width;
567 float divHeight = TWO / height;
569 // Create a buffer to render to
570 meshRecord.mBuffer = FrameBufferImage::New( width, height );
572 // Create a mesh actor to contain the post-effect render
573 MeshData::VertexContainer vertices;
574 MeshData::FaceIndices face;
576 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
580 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, tly + shadowOffset.y, ZERO ),
581 Vector2( ONE, ZERO ),
584 vertices.push_back( MeshData::Vertex( Vector3( tlx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
585 Vector2( ZERO, ONE ),
588 vertices.push_back( MeshData::Vertex( Vector3( brx + shadowOffset.x, bry + shadowOffset.y, ZERO ),
593 Material newMaterial = Material::New("effect buffer");
594 newMaterial.SetDiffuseTexture( meshRecord.mBuffer );
595 meshData.SetMaterial( newMaterial );
596 meshData.SetVertices( vertices );
597 meshData.SetFaceIndices( mFace );
598 meshData.SetHasNormals( true );
599 meshData.SetHasColor( false );
600 meshData.SetHasTextureCoords( true );
601 MeshActor actor = MeshActor::New( Mesh::New( meshData ) );
602 actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
603 actor.SetShaderEffect( mBgraShader );
604 actor.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
605 actor.SetSortModifier( 0.1f ); // force behind main text
607 // Create a sub actor to render once with normalized vertex positions
608 MeshData newMeshData;
609 MeshData::VertexContainer newVerts;
610 MeshData::FaceIndices newFaces;
611 MeshData::FaceIndices faces = meshRecord.mMeshData.GetFaces();
612 for ( uint32_t i = 0; i < verts.size(); ++i )
614 MeshData::Vertex vertex = verts[ i ];
615 vertex.x = ( ( vertex.x - tlx ) * divWidth ) - ONE;
616 vertex.y = ( ( vertex.y - tly ) * divHeight ) - ONE;
617 newVerts.push_back( vertex );
620 // Reverse triangle winding order
621 uint32_t faceCount = faces.size() / 3;
622 for ( uint32_t i = 0; i < faceCount; ++i )
624 uint32_t index = i * 3;
625 newFaces.push_back( faces[ index + 2 ] );
626 newFaces.push_back( faces[ index + 1 ] );
627 newFaces.push_back( faces[ index ] );
630 newMeshData.SetMaterial( meshRecord.mMeshData.GetMaterial() );
631 newMeshData.SetVertices( newVerts );
632 newMeshData.SetFaceIndices( newFaces );
633 newMeshData.SetHasNormals( true );
634 newMeshData.SetHasColor( false );
635 newMeshData.SetHasTextureCoords( true );
637 MeshActor subActor = MeshActor::New( Mesh::New( newMeshData ) );
638 subActor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
639 subActor.SetColor( shadowColor );
640 subActor.SetShaderEffect( mBasicShadowShader );
641 subActor.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
643 // Create a render task to render the effect
644 RenderTask task = Stage::GetCurrent().GetRenderTaskList().CreateTask();
645 task.SetTargetFrameBuffer( meshRecord.mBuffer );
646 task.SetSourceActor( subActor );
647 task.SetClearEnabled( true );
648 task.SetClearColor( Vector4::ZERO );
649 task.SetExclusive( true );
650 task.SetRefreshRate( RenderTask::REFRESH_ONCE );
651 task.FinishedSignal().Connect( this, &AtlasRenderer::Impl::RenderComplete );
652 actor.Add( subActor );
656 void RenderComplete( RenderTask& renderTask )
658 // Disconnect and remove this single shot render task
659 renderTask.FinishedSignal().Disconnect( this, &AtlasRenderer::Impl::RenderComplete );
660 Stage::GetCurrent().GetRenderTaskList().RemoveTask( renderTask );
662 // Get the actor used for render to buffer and remove it from the parent
663 Actor renderActor = renderTask.GetSourceActor();
666 Actor parent = renderActor.GetParent();
669 parent.Remove( renderActor );
674 RenderableActor mActor; ///< The actor parent which renders the text
675 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
676 Vector< uint32_t > mImageIds; ///< A list of imageIDs used by the renderer
677 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
678 ShaderEffect mBasicShader; ///> Shader used to render L8 glyphs
679 ShaderEffect mBgraShader; ///> Shader used to render BGRA glyphs
680 ShaderEffect mBasicShadowShader; ///> Shader used to render drop shadow into buffer
681 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
682 std::vector< MeshData::FaceIndex > mFace; ///> Face indices for a quad
685 Text::RendererPtr AtlasRenderer::New()
687 return Text::RendererPtr( new AtlasRenderer() );
690 RenderableActor AtlasRenderer::Render( Text::ViewInterface& view )
693 UnparentAndReset( mImpl->mActor );
695 Text::Length numberOfGlyphs = view.GetNumberOfGlyphs();
697 if( numberOfGlyphs > 0 )
699 Vector<GlyphInfo> glyphs;
700 glyphs.Resize( numberOfGlyphs );
702 view.GetGlyphs( &glyphs[0], 0, numberOfGlyphs );
704 std::vector<Vector2> positions;
705 positions.resize( numberOfGlyphs );
706 view.GetGlyphPositions( &positions[0], 0, numberOfGlyphs );
707 mImpl->AddGlyphs( positions,
710 view.GetShadowOffset(),
711 view.GetShadowColor(),
712 view.IsUnderlineEnabled(),
713 view.GetUnderlineColor(),
714 view.GetUnderlineHeight() );
716 return mImpl->mActor;
719 AtlasRenderer::AtlasRenderer()
725 AtlasRenderer::~AtlasRenderer()