2 * Copyright (c) 2018 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/visuals/texture-manager-impl.h>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/devel-api/adaptor-framework/environment-variable.h>
26 #include <dali/devel-api/adaptor-framework/image-loading.h>
27 #include <dali/devel-api/common/hash.h>
28 #include <dali/devel-api/images/texture-set-image.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30 #include <dali/integration-api/debug.h>
33 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
34 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
40 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
41 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
43 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
44 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
46 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
48 using Dali::EnvironmentVariable::GetEnvironmentVariable;
49 auto numberString = GetEnvironmentVariable(environmentVariable);
50 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
51 constexpr auto MAX_NUMBER_OF_THREADS = 100u;
52 DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
53 return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
56 size_t GetNumberOfLocalLoaderThreads()
58 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
61 size_t GetNumberOfRemoteLoaderThreads()
63 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
81 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
84 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
85 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
86 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
87 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
90 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
92 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
94 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
96 pixelBuffer.MultiplyColorByAlpha();
101 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
105 } // Anonymous namespace
107 TextureManager::MaskingData::MaskingData()
109 mAlphaMaskId( INVALID_TEXTURE_ID ),
110 mContentScaleFactor( 1.0f ),
115 TextureManager::TextureManager()
116 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
117 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
119 mLifecycleObservers(),
121 mCurrentTextureId( 0 )
125 TextureManager::~TextureManager()
127 for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
129 (*iter)->TextureManagerDestroyed();
133 TextureSet TextureManager::LoadTexture(
134 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
135 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
136 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
137 Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
138 Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
139 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
140 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
142 TextureSet textureSet;
144 loadingStatus = false;
145 textureRect = FULL_ATLAS_RECT;
147 if( VisualUrl::TEXTURE == url.GetProtocolType())
149 std::string location = url.GetLocation();
150 if( location.size() > 0u )
152 TextureId id = std::stoi( location );
153 for( auto&& elem : mExternalTextures )
155 if( elem.textureId == id )
157 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
158 textureId = elem.textureId;
159 return elem.textureSet;
164 else if( synchronousLoading )
169 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
170 orientationCorrection );
173 PreMultiply( pixelBuffer, preMultiplyOnLoad );
174 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
180 textureSet = TextureSet::New();
181 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
184 PreMultiply( pixelBuffer, preMultiplyOnLoad );
185 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
187 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
188 data.GetWidth(), data.GetHeight() );
189 texture.Upload( data );
190 textureSet = TextureSet::New();
191 textureSet.SetTexture( 0u, texture );
195 if( atlasingStatus ) // attempt atlasing
197 textureSet = imageAtlasManager->Add( textureRect, data );
199 if( !textureSet ) // big image, no atlasing or atlasing failed
201 atlasingStatus = false;
202 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
203 data.GetWidth(), data.GetHeight() );
204 texture.Upload( data );
205 textureSet = TextureSet::New();
206 textureSet.SetTexture( 0u, texture );
210 textureRectSize.SetWidth(data.GetWidth());
211 textureRectSize.SetHeight(data.GetHeight());
217 loadingStatus = true;
220 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
222 if( !textureSet ) // big image, no atlasing or atlasing failed
224 atlasingStatus = false;
227 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
228 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
232 textureId = RequestLoad( url,
233 maskInfo->mAlphaMaskId,
234 maskInfo->mContentScaleFactor,
236 fittingMode, samplingMode,
237 TextureManager::NO_ATLAS,
238 maskInfo->mCropToMask,
240 orientationCorrection,
241 reloadPolicy, preMultiplyOnLoad );
244 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
247 case TextureManager::NOT_STARTED :
248 case TextureManager::LOADING :
249 case TextureManager::LOAD_FAILED :
251 loadingStatus = true;
256 loadingStatus = false;
261 if( loadState == TextureManager::UPLOADED )
263 // UploadComplete has already been called - keep the same texture set
264 textureSet = GetTextureSet( textureId );
269 textureRectSize = desiredSize;
273 if( ! atlasingStatus && textureSet )
275 Sampler sampler = Sampler::New();
276 sampler.SetWrapMode( wrapModeU, wrapModeV );
277 textureSet.SetSampler( 0u, sampler );
283 TextureManager::TextureId TextureManager::RequestLoad(
284 const VisualUrl& url,
285 const ImageDimensions desiredSize,
286 FittingMode::Type fittingMode,
287 Dali::SamplingMode::Type samplingMode,
288 const UseAtlas useAtlas,
289 TextureUploadObserver* observer,
290 bool orientationCorrection,
291 TextureManager::ReloadPolicy reloadPolicy,
292 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
294 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
295 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
299 TextureManager::TextureId TextureManager::RequestLoad(
300 const VisualUrl& url,
301 TextureId maskTextureId,
303 const ImageDimensions desiredSize,
304 FittingMode::Type fittingMode,
305 Dali::SamplingMode::Type samplingMode,
306 const UseAtlas useAtlas,
308 TextureUploadObserver* observer,
309 bool orientationCorrection,
310 TextureManager::ReloadPolicy reloadPolicy,
311 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
313 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
314 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
318 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
320 // Use the normal load procedure to get the alpha mask.
321 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
322 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
323 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
324 TextureManager::ReloadPolicy::CACHED, preMultiply );
327 TextureManager::TextureId TextureManager::RequestLoadInternal(
328 const VisualUrl& url,
329 TextureId maskTextureId,
331 const ImageDimensions desiredSize,
332 FittingMode::Type fittingMode,
333 Dali::SamplingMode::Type samplingMode,
336 StorageType storageType,
337 TextureUploadObserver* observer,
338 bool orientationCorrection,
339 TextureManager::ReloadPolicy reloadPolicy,
340 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
342 // First check if the requested Texture is cached.
343 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
344 maskTextureId, preMultiplyOnLoad );
346 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
348 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
349 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
350 maskTextureId, preMultiplyOnLoad );
352 // Check if the requested Texture exists in the cache.
353 if( cacheIndex != INVALID_CACHE_INDEX )
355 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
357 // Mark this texture being used by another client resource. Forced reload would replace the current texture
358 // without the need for incrementing the reference count.
359 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
361 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
362 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
363 url.GetUrl().c_str(), observer, cacheIndex, textureId );
366 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
368 // We need a new Texture.
369 textureId = GenerateUniqueTextureId();
370 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
371 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
372 desiredSize, contentScale, fittingMode, samplingMode,
373 false, cropToMask, useAtlas, textureHash, orientationCorrection,
375 cacheIndex = mTextureInfoContainer.size() - 1u;
377 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
378 url.GetUrl().c_str(), observer, cacheIndex, textureId );
381 // The below code path is common whether we are using the cache or not.
382 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
383 // or a new TextureInfo just created.
384 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
385 textureInfo.maskTextureId = maskTextureId;
386 textureInfo.storageType = storageType;
387 textureInfo.orientationCorrection = orientationCorrection;
389 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
390 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
391 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
392 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
393 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
395 // Force reloading of texture by setting loadState unless already loading or cancelled.
396 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
397 TextureManager::CANCELLED != textureInfo.loadState )
399 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
400 url.GetUrl().c_str(), observer, cacheIndex, textureId );
401 textureInfo.loadState = TextureManager::NOT_STARTED;
404 // Check if we should add the observer.
405 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
406 switch( textureInfo.loadState )
408 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
409 case TextureManager::NOT_STARTED:
411 LoadTexture( textureInfo );
412 ObserveTexture( textureInfo, observer );
415 case TextureManager::LOADING:
417 ObserveTexture( textureInfo, observer );
420 case TextureManager::UPLOADED:
424 // The Texture has already loaded. The other observers have already been notified.
425 // We need to send a "late" loaded notification for this observer.
426 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
427 textureInfo.useAtlas, textureInfo.atlasRect,
428 textureInfo.preMultiplied );
432 case TextureManager::CANCELLED:
434 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
435 // (it's ref count has already been incremented, above)
436 textureInfo.loadState = TextureManager::LOADING;
437 ObserveTexture( textureInfo, observer );
440 case TextureManager::LOAD_FINISHED:
441 case TextureManager::WAITING_FOR_MASK:
442 // Loading has already completed. Do nothing.
446 // Return the TextureId for which this Texture can now be referenced by externally.
450 void TextureManager::Remove( const TextureManager::TextureId textureId )
452 int textureInfoIndex = GetCacheIndexFromId( textureId );
453 if( textureInfoIndex != INVALID_INDEX )
455 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
457 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
458 textureId, textureInfoIndex,
459 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
460 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
461 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
462 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
464 // Decrement the reference count and check if this is the last user of this Texture.
465 if( --textureInfo.referenceCount <= 0 )
467 // This is the last remove for this Texture.
468 textureInfo.referenceCount = 0;
469 bool removeTextureInfo = false;
471 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
472 if( textureInfo.loadState == UPLOADED )
474 if( textureInfo.atlas )
476 textureInfo.atlas.Remove( textureInfo.atlasRect );
478 removeTextureInfo = true;
480 else if( textureInfo.loadState == LOADING )
482 // We mark the textureInfo for removal.
483 // Once the load has completed, this method will be called again.
484 textureInfo.loadState = CANCELLED;
488 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
489 removeTextureInfo = true;
492 // If the state allows us to remove the TextureInfo data, we do so.
493 if( removeTextureInfo )
495 // Permanently remove the textureInfo struct.
496 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
502 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
504 VisualUrl visualUrl("");
505 int cacheIndex = GetCacheIndexFromId( textureId );
507 if( cacheIndex != INVALID_CACHE_INDEX )
509 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
510 cacheIndex, textureId );
512 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
513 visualUrl = cachedTextureInfo.url;
518 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
520 LoadState loadState = TextureManager::NOT_STARTED;
522 int cacheIndex = GetCacheIndexFromId( textureId );
523 if( cacheIndex != INVALID_CACHE_INDEX )
525 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
526 loadState = cachedTextureInfo.loadState;
530 for( auto&& elem : mExternalTextures )
532 if( elem.textureId == textureId )
534 loadState = LoadState::UPLOADED;
542 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
544 LoadState loadState = TextureManager::NOT_STARTED;
546 int cacheIndex = GetCacheIndexFromId( textureId );
547 if( cacheIndex != INVALID_CACHE_INDEX )
549 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
550 loadState = cachedTextureInfo.loadState;
556 TextureSet TextureManager::GetTextureSet( TextureId textureId )
558 TextureSet textureSet;// empty handle
560 int cacheIndex = GetCacheIndexFromId( textureId );
561 if( cacheIndex != INVALID_CACHE_INDEX )
563 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
564 textureSet = cachedTextureInfo.textureSet;
568 for( auto&& elem : mExternalTextures )
570 if( elem.textureId == textureId )
572 textureSet = elem.textureSet;
580 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
582 TextureManager::ExternalTextureInfo info;
583 info.textureId = GenerateUniqueTextureId();
584 info.textureSet = textureSet;
585 mExternalTextures.emplace_back( info );
586 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
589 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
591 if( url.size() > 0u )
593 // get the location from the Url
594 VisualUrl parseUrl( url );
595 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
597 std::string location = parseUrl.GetLocation();
598 if( location.size() > 0u )
600 TextureId id = std::stoi( location );
601 const auto end = mExternalTextures.end();
602 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
604 if( iter->textureId == id )
606 auto textureSet = iter->textureSet;
607 mExternalTextures.erase( iter );
618 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
620 // make sure an observer doesn't observe the same object twice
621 // otherwise it will get multiple calls to ObjectDestroyed()
622 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
623 mLifecycleObservers.PushBack( &observer );
626 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
628 // Find the observer...
629 auto endIter = mLifecycleObservers.End();
630 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
632 if( (*iter) == &observer)
634 mLifecycleObservers.Erase( iter );
638 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
642 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
646 if( textureInfo.loadState == NOT_STARTED )
648 textureInfo.loadState = LOADING;
650 if( !textureInfo.loadSynchronously )
652 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
653 auto loadingHelperIt = loadersContainer.GetNext();
654 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
655 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
656 textureInfo.desiredSize, textureInfo.fittingMode,
657 textureInfo.samplingMode, textureInfo.orientationCorrection );
664 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
665 TextureUploadObserver* observer )
669 textureInfo.observerList.PushBack( observer );
670 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
674 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
675 Devel::PixelBuffer pixelBuffer )
677 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
679 if( loadingContainer.size() >= 1u )
681 AsyncLoadingInfo loadingInfo = loadingContainer.front();
683 if( loadingInfo.loadId == id )
685 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
686 if( cacheIndex != INVALID_CACHE_INDEX )
688 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
690 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
692 if( textureInfo.loadState != CANCELLED )
694 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
695 PostLoad( textureInfo, pixelBuffer );
699 Remove( textureInfo.textureId );
704 loadingContainer.pop_front();
708 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
710 // Was the load successful?
711 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
713 // No atlas support for now
714 textureInfo.useAtlas = NO_ATLAS;
716 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
718 // If there is a mask texture ID associated with this texture, then apply the mask
719 // if it's already loaded. If it hasn't, and the mask is still loading,
720 // wait for the mask to finish loading.
721 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
723 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
724 if( maskLoadState == LOADING )
726 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
727 textureInfo.loadState = WAITING_FOR_MASK;
729 else if( maskLoadState == LOAD_FINISHED )
731 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
732 UploadTexture( pixelBuffer, textureInfo );
733 NotifyObservers( textureInfo, true );
738 UploadTexture( pixelBuffer, textureInfo );
739 NotifyObservers( textureInfo, true );
744 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
745 textureInfo.loadState = LOAD_FINISHED;
747 // Check if there was another texture waiting for this load to complete
748 // (e.g. if this was an image mask, and its load is on a different thread)
749 CheckForWaitingTexture( textureInfo );
754 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
755 // @todo If the load was unsuccessful, upload the broken image.
756 textureInfo.loadState = LOAD_FAILED;
757 CheckForWaitingTexture( textureInfo );
758 NotifyObservers( textureInfo, false );
762 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
764 // Search the cache, checking if any texture has this texture id as a
766 const unsigned int size = mTextureInfoContainer.size();
768 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
770 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
771 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
773 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
774 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
775 textureInfo.pixelBuffer.Reset();
777 if( maskTextureInfo.loadState == LOAD_FINISHED )
779 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
780 UploadTexture( pixelBuffer, textureInfo );
781 NotifyObservers( textureInfo, true );
785 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
786 textureInfo.loadState = LOAD_FAILED;
787 NotifyObservers( textureInfo, false );
793 void TextureManager::ApplyMask(
794 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
795 float contentScale, bool cropToMask )
797 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
798 if( maskCacheIndex != INVALID_CACHE_INDEX )
800 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
801 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
806 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
808 if( textureInfo.useAtlas != USE_ATLAS )
810 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
812 // If the texture doesn't have an alpha channel, can't pre-multiply it.
813 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
814 // the status for use in the observer.
815 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
816 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
817 PreMultiply( pixelBuffer, preMultiply );
818 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
820 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
821 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
823 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
824 texture.Upload( pixelData );
825 if ( ! textureInfo.textureSet )
827 textureInfo.textureSet = TextureSet::New();
829 textureInfo.textureSet.SetTexture( 0u, texture );
832 // Update the load state.
833 // Note: This is regardless of success as we care about whether a
834 // load attempt is in progress or not. If unsuccessful, a broken
835 // image is still loaded.
836 textureInfo.loadState = UPLOADED;
839 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
841 TextureId textureId = textureInfo.textureId;
843 // If there is an observer: Notify the load is complete, whether successful or not,
844 // and erase it from the list
845 unsigned int observerCount = textureInfo.observerList.Count();
846 TextureInfo* info = &textureInfo;
848 while( observerCount )
850 TextureUploadObserver* observer = info->observerList[0];
852 // During UploadComplete() a Control ResourceReady() signal is emitted.
853 // During that signal the app may add remove /add Textures (e.g. via
854 // ImageViews). At this point no more observers can be added to the
855 // observerList, because textureInfo.loadState = UPLOADED. However it is
856 // possible for observers to be removed, hence we check the observer list
857 // count every iteration.
859 // The reference to the textureInfo struct can also become invalidated,
860 // because new load requests can modify the mTextureInfoContainer list
861 // (e.g. if more requests are pushed back it can cause the list to be
862 // resized invalidating the reference to the TextureInfo ).
863 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
864 info->preMultiplied );
865 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
867 // Get the textureInfo from the container again as it may have been
870 int textureInfoIndex = GetCacheIndexFromId( textureId );
871 if( textureInfoIndex == INVALID_CACHE_INDEX)
873 return; // texture has been removed - can stop.
876 info = &mTextureInfoContainer[ textureInfoIndex ];
877 observerCount = info->observerList.Count();
878 if ( observerCount > 0 )
880 // remove the observer that was just triggered if it's still in the list
881 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
885 info->observerList.Erase( j );
894 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
896 return mCurrentTextureId++;
899 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
901 const unsigned int size = mTextureInfoContainer.size();
903 for( unsigned int i = 0; i < size; ++i )
905 if( mTextureInfoContainer[i].textureId == textureId )
911 return INVALID_CACHE_INDEX;
914 TextureManager::TextureHash TextureManager::GenerateHash(
915 const std::string& url,
916 const ImageDimensions size,
917 const FittingMode::Type fittingMode,
918 const Dali::SamplingMode::Type samplingMode,
919 const UseAtlas useAtlas,
920 TextureId maskTextureId,
921 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
923 std::string hashTarget( url );
924 const size_t urlLength = hashTarget.length();
925 const uint16_t width = size.GetWidth();
926 const uint16_t height = size.GetWidth();
928 // If either the width or height has been specified, include the resizing options in the hash
929 if( width != 0 || height != 0 )
931 // We are appending 5 bytes to the URL to form the hash input.
932 hashTarget.resize( urlLength + 5u );
933 char* hashTargetPtr = &( hashTarget[ urlLength ] );
935 // Pack the width and height (4 bytes total).
936 *hashTargetPtr++ = size.GetWidth() & 0xff;
937 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
938 *hashTargetPtr++ = size.GetHeight() & 0xff;
939 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
941 // Bit-pack the FittingMode, SamplingMode and atlasing.
942 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
943 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
947 // We are not including sizing information, but we still need an extra byte for atlasing.
948 hashTarget.resize( urlLength + 1u );
950 // Add the atlasing to the hash input.
953 case UseAtlas::NO_ATLAS:
955 hashTarget[ urlLength ] = 'f';
958 case UseAtlas::USE_ATLAS:
960 hashTarget[ urlLength ] = 't';
966 if( maskTextureId != INVALID_TEXTURE_ID )
968 auto textureIdIndex = hashTarget.length();
969 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
970 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
972 // Append the texture id to the end of the URL byte by byte:
973 // (to avoid SIGBUS / alignment issues)
974 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
976 *hashTargetPtr++ = maskTextureId & 0xff;
977 maskTextureId >>= 8u;
981 auto premultipliedIndex = hashTarget.length();
982 hashTarget.resize( premultipliedIndex + 1 );
983 switch( preMultiplyOnLoad )
985 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
987 hashTarget[ premultipliedIndex ] = 't';
990 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
992 hashTarget[ premultipliedIndex ] = 'f';
997 return Dali::CalculateHash( hashTarget );
1000 int TextureManager::FindCachedTexture(
1001 const TextureManager::TextureHash hash,
1002 const std::string& url,
1003 const ImageDimensions size,
1004 const FittingMode::Type fittingMode,
1005 const Dali::SamplingMode::Type samplingMode,
1006 const bool useAtlas,
1007 TextureId maskTextureId,
1008 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
1010 // Default to an invalid ID, in case we do not find a match.
1011 int cacheIndex = INVALID_CACHE_INDEX;
1013 // Iterate through our hashes to find a match.
1014 const unsigned int count = mTextureInfoContainer.size();
1015 for( unsigned int i = 0u; i < count; ++i )
1017 if( mTextureInfoContainer[i].hash == hash )
1019 // We have a match, now we check all the original parameters in case of a hash collision.
1020 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1021 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
1022 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
1024 if( ( url == textureInfo.url.GetUrl() ) &&
1025 ( useAtlas == textureInfo.useAtlas ) &&
1026 ( maskTextureId == textureInfo.maskTextureId ) &&
1027 ( size == textureInfo.desiredSize ) &&
1028 ( preMultiplyOnLoad == multiplyOnLoad ) &&
1029 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1030 ( fittingMode == textureInfo.fittingMode &&
1031 samplingMode == textureInfo.samplingMode ) ) )
1033 // The found Texture is a match.
1043 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1045 const unsigned int count = mTextureInfoContainer.size();
1046 for( unsigned int i = 0; i < count; ++i )
1048 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1049 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1050 j != textureInfo.observerList.End(); )
1052 if( *j == observer )
1054 j = textureInfo.observerList.Erase( j );
1065 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1066 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1067 AsyncLoadingInfoContainerType())
1071 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1072 const VisualUrl& url,
1073 ImageDimensions desiredSize,
1074 FittingMode::Type fittingMode,
1075 SamplingMode::Type samplingMode,
1076 bool orientationCorrection)
1078 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1079 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1080 mLoadingInfoContainer.back().loadId = id;
1083 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1084 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1088 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1089 Toolkit::AsyncImageLoader loader,
1090 TextureManager& textureManager,
1091 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1093 mTextureManager(textureManager),
1094 mLoadingInfoContainer(std::move(loadingInfoContainer))
1096 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1097 this, &AsyncLoadingHelper::AsyncLoadComplete);
1100 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1101 Devel::PixelBuffer pixelBuffer)
1103 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1106 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1108 mBrokenImageUrl = brokenImageUrl;
1111 } // namespace Internal
1113 } // namespace Toolkit