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 );
245 loadingStatus = ( loadState == TextureManager::LOADING );
247 if( loadState == TextureManager::UPLOADED )
249 // UploadComplete has already been called - keep the same texture set
250 textureSet = GetTextureSet( textureId );
255 textureRectSize = desiredSize;
259 if( ! atlasingStatus && textureSet )
261 Sampler sampler = Sampler::New();
262 sampler.SetWrapMode( wrapModeU, wrapModeV );
263 textureSet.SetSampler( 0u, sampler );
269 TextureManager::TextureId TextureManager::RequestLoad(
270 const VisualUrl& url,
271 const ImageDimensions desiredSize,
272 FittingMode::Type fittingMode,
273 Dali::SamplingMode::Type samplingMode,
274 const UseAtlas useAtlas,
275 TextureUploadObserver* observer,
276 bool orientationCorrection,
277 TextureManager::ReloadPolicy reloadPolicy,
278 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
280 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
281 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
285 TextureManager::TextureId TextureManager::RequestLoad(
286 const VisualUrl& url,
287 TextureId maskTextureId,
289 const ImageDimensions desiredSize,
290 FittingMode::Type fittingMode,
291 Dali::SamplingMode::Type samplingMode,
292 const UseAtlas useAtlas,
294 TextureUploadObserver* observer,
295 bool orientationCorrection,
296 TextureManager::ReloadPolicy reloadPolicy,
297 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
299 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
300 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
304 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
306 // Use the normal load procedure to get the alpha mask.
307 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
308 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
309 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
310 TextureManager::ReloadPolicy::CACHED, preMultiply );
313 TextureManager::TextureId TextureManager::RequestLoadInternal(
314 const VisualUrl& url,
315 TextureId maskTextureId,
317 const ImageDimensions desiredSize,
318 FittingMode::Type fittingMode,
319 Dali::SamplingMode::Type samplingMode,
322 StorageType storageType,
323 TextureUploadObserver* observer,
324 bool orientationCorrection,
325 TextureManager::ReloadPolicy reloadPolicy,
326 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
328 // First check if the requested Texture is cached.
329 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
330 maskTextureId, preMultiplyOnLoad );
332 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
334 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
335 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
336 maskTextureId, preMultiplyOnLoad );
338 // Check if the requested Texture exists in the cache.
339 if( cacheIndex != INVALID_CACHE_INDEX )
341 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
343 // Mark this texture being used by another client resource. Forced reload would replace the current texture
344 // without the need for incrementing the reference count.
345 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
347 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
348 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
349 url.GetUrl().c_str(), observer, cacheIndex, textureId );
352 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
354 // We need a new Texture.
355 textureId = GenerateUniqueTextureId();
356 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
357 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
358 desiredSize, contentScale, fittingMode, samplingMode,
359 false, cropToMask, useAtlas, textureHash, orientationCorrection,
361 cacheIndex = mTextureInfoContainer.size() - 1u;
363 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
364 url.GetUrl().c_str(), observer, cacheIndex, textureId );
367 // The below code path is common whether we are using the cache or not.
368 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
369 // or a new TextureInfo just created.
370 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
371 textureInfo.maskTextureId = maskTextureId;
372 textureInfo.storageType = storageType;
373 textureInfo.orientationCorrection = orientationCorrection;
375 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
376 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
377 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
378 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
379 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
381 // Force reloading of texture by setting loadState unless already loading or cancelled.
382 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
383 TextureManager::CANCELLED != textureInfo.loadState )
385 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
386 url.GetUrl().c_str(), observer, cacheIndex, textureId );
387 textureInfo.loadState = TextureManager::NOT_STARTED;
390 // Check if we should add the observer.
391 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
392 switch( textureInfo.loadState )
394 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
395 case TextureManager::NOT_STARTED:
397 LoadTexture( textureInfo );
398 ObserveTexture( textureInfo, observer );
401 case TextureManager::LOADING:
403 ObserveTexture( textureInfo, observer );
406 case TextureManager::UPLOADED:
410 // The Texture has already loaded. The other observers have already been notified.
411 // We need to send a "late" loaded notification for this observer.
412 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
413 textureInfo.useAtlas, textureInfo.atlasRect,
414 textureInfo.preMultiplied );
418 case TextureManager::CANCELLED:
420 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
421 // (it's ref count has already been incremented, above)
422 textureInfo.loadState = TextureManager::LOADING;
423 ObserveTexture( textureInfo, observer );
426 case TextureManager::LOAD_FINISHED:
427 case TextureManager::WAITING_FOR_MASK:
428 // Loading has already completed. Do nothing.
432 // Return the TextureId for which this Texture can now be referenced by externally.
436 void TextureManager::Remove( const TextureManager::TextureId textureId )
438 int textureInfoIndex = GetCacheIndexFromId( textureId );
439 if( textureInfoIndex != INVALID_INDEX )
441 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
443 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
444 textureId, textureInfoIndex,
445 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
446 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
447 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
448 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
450 // Decrement the reference count and check if this is the last user of this Texture.
451 if( --textureInfo.referenceCount <= 0 )
453 // This is the last remove for this Texture.
454 textureInfo.referenceCount = 0;
455 bool removeTextureInfo = false;
457 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
458 if( textureInfo.loadState == UPLOADED )
460 if( textureInfo.atlas )
462 textureInfo.atlas.Remove( textureInfo.atlasRect );
464 removeTextureInfo = true;
466 else if( textureInfo.loadState == LOADING )
468 // We mark the textureInfo for removal.
469 // Once the load has completed, this method will be called again.
470 textureInfo.loadState = CANCELLED;
474 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
475 removeTextureInfo = true;
478 // If the state allows us to remove the TextureInfo data, we do so.
479 if( removeTextureInfo )
481 // Permanently remove the textureInfo struct.
482 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
488 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
490 VisualUrl visualUrl("");
491 int cacheIndex = GetCacheIndexFromId( textureId );
493 if( cacheIndex != INVALID_CACHE_INDEX )
495 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
496 cacheIndex, textureId );
498 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
499 visualUrl = cachedTextureInfo.url;
504 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
506 LoadState loadState = TextureManager::NOT_STARTED;
508 int cacheIndex = GetCacheIndexFromId( textureId );
509 if( cacheIndex != INVALID_CACHE_INDEX )
511 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
512 loadState = cachedTextureInfo.loadState;
516 for( auto&& elem : mExternalTextures )
518 if( elem.textureId == textureId )
520 loadState = LoadState::UPLOADED;
528 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
530 LoadState loadState = TextureManager::NOT_STARTED;
532 int cacheIndex = GetCacheIndexFromId( textureId );
533 if( cacheIndex != INVALID_CACHE_INDEX )
535 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
536 loadState = cachedTextureInfo.loadState;
542 TextureSet TextureManager::GetTextureSet( TextureId textureId )
544 TextureSet textureSet;// empty handle
546 int cacheIndex = GetCacheIndexFromId( textureId );
547 if( cacheIndex != INVALID_CACHE_INDEX )
549 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
550 textureSet = cachedTextureInfo.textureSet;
554 for( auto&& elem : mExternalTextures )
556 if( elem.textureId == textureId )
558 textureSet = elem.textureSet;
566 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
568 TextureManager::ExternalTextureInfo info;
569 info.textureId = GenerateUniqueTextureId();
570 info.textureSet = textureSet;
571 mExternalTextures.emplace_back( info );
572 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
575 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
577 if( url.size() > 0u )
579 // get the location from the Url
580 VisualUrl parseUrl( url );
581 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
583 std::string location = parseUrl.GetLocation();
584 if( location.size() > 0u )
586 TextureId id = std::stoi( location );
587 const auto end = mExternalTextures.end();
588 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
590 if( iter->textureId == id )
592 auto textureSet = iter->textureSet;
593 mExternalTextures.erase( iter );
604 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
606 // make sure an observer doesn't observe the same object twice
607 // otherwise it will get multiple calls to ObjectDestroyed()
608 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
609 mLifecycleObservers.PushBack( &observer );
612 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
614 // Find the observer...
615 auto endIter = mLifecycleObservers.End();
616 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
618 if( (*iter) == &observer)
620 mLifecycleObservers.Erase( iter );
624 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
628 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
632 if( textureInfo.loadState == NOT_STARTED )
634 textureInfo.loadState = LOADING;
636 if( !textureInfo.loadSynchronously )
638 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
639 auto loadingHelperIt = loadersContainer.GetNext();
640 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
641 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
642 textureInfo.desiredSize, textureInfo.fittingMode,
643 textureInfo.samplingMode, textureInfo.orientationCorrection );
650 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
651 TextureUploadObserver* observer )
655 textureInfo.observerList.PushBack( observer );
656 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
660 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
661 Devel::PixelBuffer pixelBuffer )
663 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
665 if( loadingContainer.size() >= 1u )
667 AsyncLoadingInfo loadingInfo = loadingContainer.front();
669 if( loadingInfo.loadId == id )
671 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
672 if( cacheIndex != INVALID_CACHE_INDEX )
674 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
676 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
678 if( textureInfo.loadState != CANCELLED )
680 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
681 PostLoad( textureInfo, pixelBuffer );
685 Remove( textureInfo.textureId );
690 loadingContainer.pop_front();
694 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
696 // Was the load successful?
697 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
699 // No atlas support for now
700 textureInfo.useAtlas = NO_ATLAS;
702 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
704 // If there is a mask texture ID associated with this texture, then apply the mask
705 // if it's already loaded. If it hasn't, and the mask is still loading,
706 // wait for the mask to finish loading.
707 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
709 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
710 if( maskLoadState == LOADING )
712 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
713 textureInfo.loadState = WAITING_FOR_MASK;
715 else if( maskLoadState == LOAD_FINISHED )
717 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
718 UploadTexture( pixelBuffer, textureInfo );
719 NotifyObservers( textureInfo, true );
724 UploadTexture( pixelBuffer, textureInfo );
725 NotifyObservers( textureInfo, true );
730 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
731 textureInfo.loadState = LOAD_FINISHED;
733 // Check if there was another texture waiting for this load to complete
734 // (e.g. if this was an image mask, and its load is on a different thread)
735 CheckForWaitingTexture( textureInfo );
740 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
741 // @todo If the load was unsuccessful, upload the broken image.
742 textureInfo.loadState = LOAD_FAILED;
743 CheckForWaitingTexture( textureInfo );
744 NotifyObservers( textureInfo, false );
748 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
750 // Search the cache, checking if any texture has this texture id as a
752 const unsigned int size = mTextureInfoContainer.size();
754 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
756 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
757 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
759 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
760 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
761 textureInfo.pixelBuffer.Reset();
763 if( maskTextureInfo.loadState == LOAD_FINISHED )
765 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
766 UploadTexture( pixelBuffer, textureInfo );
767 NotifyObservers( textureInfo, true );
771 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
772 textureInfo.loadState = LOAD_FAILED;
773 NotifyObservers( textureInfo, false );
779 void TextureManager::ApplyMask(
780 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
781 float contentScale, bool cropToMask )
783 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
784 if( maskCacheIndex != INVALID_CACHE_INDEX )
786 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
787 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
792 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
794 if( textureInfo.useAtlas != USE_ATLAS )
796 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
798 // If the texture doesn't have an alpha channel, can't pre-multiply it.
799 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
800 // the status for use in the observer.
801 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
802 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
803 PreMultiply( pixelBuffer, preMultiply );
804 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
806 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
807 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
809 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
810 texture.Upload( pixelData );
811 if ( ! textureInfo.textureSet )
813 textureInfo.textureSet = TextureSet::New();
815 textureInfo.textureSet.SetTexture( 0u, texture );
818 // Update the load state.
819 // Note: This is regardless of success as we care about whether a
820 // load attempt is in progress or not. If unsuccessful, a broken
821 // image is still loaded.
822 textureInfo.loadState = UPLOADED;
825 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
827 TextureId textureId = textureInfo.textureId;
829 // If there is an observer: Notify the load is complete, whether successful or not,
830 // and erase it from the list
831 unsigned int observerCount = textureInfo.observerList.Count();
832 TextureInfo* info = &textureInfo;
834 while( observerCount )
836 TextureUploadObserver* observer = info->observerList[0];
838 // During UploadComplete() a Control ResourceReady() signal is emitted.
839 // During that signal the app may add remove /add Textures (e.g. via
840 // ImageViews). At this point no more observers can be added to the
841 // observerList, because textureInfo.loadState = UPLOADED. However it is
842 // possible for observers to be removed, hence we check the observer list
843 // count every iteration.
845 // The reference to the textureInfo struct can also become invalidated,
846 // because new load requests can modify the mTextureInfoContainer list
847 // (e.g. if more requests are pushed back it can cause the list to be
848 // resized invalidating the reference to the TextureInfo ).
849 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
850 info->preMultiplied );
851 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
853 // Get the textureInfo from the container again as it may have been
856 int textureInfoIndex = GetCacheIndexFromId( textureId );
857 if( textureInfoIndex == INVALID_CACHE_INDEX)
859 return; // texture has been removed - can stop.
862 info = &mTextureInfoContainer[ textureInfoIndex ];
863 observerCount = info->observerList.Count();
864 if ( observerCount > 0 )
866 // remove the observer that was just triggered if it's still in the list
867 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
871 info->observerList.Erase( j );
880 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
882 return mCurrentTextureId++;
885 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
887 const unsigned int size = mTextureInfoContainer.size();
889 for( unsigned int i = 0; i < size; ++i )
891 if( mTextureInfoContainer[i].textureId == textureId )
897 return INVALID_CACHE_INDEX;
900 TextureManager::TextureHash TextureManager::GenerateHash(
901 const std::string& url,
902 const ImageDimensions size,
903 const FittingMode::Type fittingMode,
904 const Dali::SamplingMode::Type samplingMode,
905 const UseAtlas useAtlas,
906 TextureId maskTextureId,
907 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
909 std::string hashTarget( url );
910 const size_t urlLength = hashTarget.length();
911 const uint16_t width = size.GetWidth();
912 const uint16_t height = size.GetWidth();
914 // If either the width or height has been specified, include the resizing options in the hash
915 if( width != 0 || height != 0 )
917 // We are appending 5 bytes to the URL to form the hash input.
918 hashTarget.resize( urlLength + 5u );
919 char* hashTargetPtr = &( hashTarget[ urlLength ] );
921 // Pack the width and height (4 bytes total).
922 *hashTargetPtr++ = size.GetWidth() & 0xff;
923 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
924 *hashTargetPtr++ = size.GetHeight() & 0xff;
925 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
927 // Bit-pack the FittingMode, SamplingMode and atlasing.
928 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
929 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
933 // We are not including sizing information, but we still need an extra byte for atlasing.
934 hashTarget.resize( urlLength + 1u );
935 // Add the atlasing to the hash input.
936 hashTarget[ urlLength ] = useAtlas;
939 if( maskTextureId != INVALID_TEXTURE_ID )
941 auto textureIdIndex = hashTarget.length();
942 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
943 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
945 // Append the texture id to the end of the URL byte by byte:
946 // (to avoid SIGBUS / alignment issues)
947 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
949 *hashTargetPtr++ = maskTextureId & 0xff;
950 maskTextureId >>= 8u;
954 auto premultipliedIndex = hashTarget.length();
955 hashTarget.resize( premultipliedIndex + 1 );
956 switch( preMultiplyOnLoad )
958 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
960 hashTarget[ premultipliedIndex ] = 't';
963 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
965 hashTarget[ premultipliedIndex ] = 'f';
970 return Dali::CalculateHash( hashTarget );
973 int TextureManager::FindCachedTexture(
974 const TextureManager::TextureHash hash,
975 const std::string& url,
976 const ImageDimensions size,
977 const FittingMode::Type fittingMode,
978 const Dali::SamplingMode::Type samplingMode,
980 TextureId maskTextureId,
981 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
983 // Default to an invalid ID, in case we do not find a match.
984 int cacheIndex = INVALID_CACHE_INDEX;
986 // Iterate through our hashes to find a match.
987 const unsigned int count = mTextureInfoContainer.size();
988 for( unsigned int i = 0u; i < count; ++i )
990 if( mTextureInfoContainer[i].hash == hash )
992 // We have a match, now we check all the original parameters in case of a hash collision.
993 TextureInfo& textureInfo( mTextureInfoContainer[i] );
994 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
995 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
997 if( ( url == textureInfo.url.GetUrl() ) &&
998 ( useAtlas == textureInfo.useAtlas ) &&
999 ( maskTextureId == textureInfo.maskTextureId ) &&
1000 ( size == textureInfo.desiredSize ) &&
1001 ( preMultiplyOnLoad == multiplyOnLoad ) &&
1002 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1003 ( fittingMode == textureInfo.fittingMode &&
1004 samplingMode == textureInfo.samplingMode ) ) )
1006 // The found Texture is a match.
1016 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1018 const unsigned int count = mTextureInfoContainer.size();
1019 for( unsigned int i = 0; i < count; ++i )
1021 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1022 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1023 j != textureInfo.observerList.End(); )
1025 if( *j == observer )
1027 j = textureInfo.observerList.Erase( j );
1038 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1039 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1040 AsyncLoadingInfoContainerType())
1044 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1045 const VisualUrl& url,
1046 ImageDimensions desiredSize,
1047 FittingMode::Type fittingMode,
1048 SamplingMode::Type samplingMode,
1049 bool orientationCorrection)
1051 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1052 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1053 mLoadingInfoContainer.back().loadId = id;
1056 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1057 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1061 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1062 Toolkit::AsyncImageLoader loader,
1063 TextureManager& textureManager,
1064 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1066 mTextureManager(textureManager),
1067 mLoadingInfoContainer(std::move(loadingInfoContainer))
1069 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1070 this, &AsyncLoadingHelper::AsyncLoadComplete);
1073 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1074 Devel::PixelBuffer pixelBuffer)
1076 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1079 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1081 mBrokenImageUrl = brokenImageUrl;
1084 } // namespace Internal
1086 } // namespace Toolkit