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 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
138 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 );
212 loadingStatus = true;
215 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
217 if( !textureSet ) // big image, no atlasing or atlasing failed
219 atlasingStatus = false;
222 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
223 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
227 textureId = RequestLoad( url,
228 maskInfo->mAlphaMaskId,
229 maskInfo->mContentScaleFactor,
231 fittingMode, samplingMode,
232 TextureManager::NO_ATLAS,
233 maskInfo->mCropToMask,
235 orientationCorrection,
236 reloadPolicy, preMultiplyOnLoad );
239 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
240 loadingStatus = ( loadState == TextureManager::LOADING );
242 if( loadState == TextureManager::UPLOADED )
244 // UploadComplete has already been called - keep the same texture set
245 textureSet = GetTextureSet( textureId );
250 if( ! atlasingStatus && textureSet )
252 Sampler sampler = Sampler::New();
253 sampler.SetWrapMode( wrapModeU, wrapModeV );
254 textureSet.SetSampler( 0u, sampler );
260 TextureManager::TextureId TextureManager::RequestLoad(
261 const VisualUrl& url,
262 const ImageDimensions desiredSize,
263 FittingMode::Type fittingMode,
264 Dali::SamplingMode::Type samplingMode,
265 const UseAtlas useAtlas,
266 TextureUploadObserver* observer,
267 bool orientationCorrection,
268 TextureManager::ReloadPolicy reloadPolicy,
269 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
271 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
272 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
276 TextureManager::TextureId TextureManager::RequestLoad(
277 const VisualUrl& url,
278 TextureId maskTextureId,
280 const ImageDimensions desiredSize,
281 FittingMode::Type fittingMode,
282 Dali::SamplingMode::Type samplingMode,
283 const UseAtlas useAtlas,
285 TextureUploadObserver* observer,
286 bool orientationCorrection,
287 TextureManager::ReloadPolicy reloadPolicy,
288 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
290 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
291 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
295 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
297 // Use the normal load procedure to get the alpha mask.
298 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
299 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
300 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
301 TextureManager::ReloadPolicy::CACHED, preMultiply );
304 TextureManager::TextureId TextureManager::RequestLoadInternal(
305 const VisualUrl& url,
306 TextureId maskTextureId,
308 const ImageDimensions desiredSize,
309 FittingMode::Type fittingMode,
310 Dali::SamplingMode::Type samplingMode,
313 StorageType storageType,
314 TextureUploadObserver* observer,
315 bool orientationCorrection,
316 TextureManager::ReloadPolicy reloadPolicy,
317 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
319 // First check if the requested Texture is cached.
320 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
321 maskTextureId, preMultiplyOnLoad );
323 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
325 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
326 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
327 maskTextureId, preMultiplyOnLoad );
329 // Check if the requested Texture exists in the cache.
330 if( cacheIndex != INVALID_CACHE_INDEX )
332 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
334 // Mark this texture being used by another client resource. Forced reload would replace the current texture
335 // without the need for incrementing the reference count.
336 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
338 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
339 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
340 url.GetUrl().c_str(), observer, cacheIndex, textureId );
343 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
345 // We need a new Texture.
346 textureId = GenerateUniqueTextureId();
347 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
348 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
349 desiredSize, contentScale, fittingMode, samplingMode,
350 false, cropToMask, useAtlas, textureHash, orientationCorrection,
352 cacheIndex = mTextureInfoContainer.size() - 1u;
354 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
355 url.GetUrl().c_str(), observer, cacheIndex, textureId );
358 // The below code path is common whether we are using the cache or not.
359 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
360 // or a new TextureInfo just created.
361 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
362 textureInfo.maskTextureId = maskTextureId;
363 textureInfo.storageType = storageType;
364 textureInfo.orientationCorrection = orientationCorrection;
366 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
367 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
368 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
369 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
370 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
372 // Force reloading of texture by setting loadState unless already loading or cancelled.
373 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
374 TextureManager::CANCELLED != textureInfo.loadState )
376 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
377 url.GetUrl().c_str(), observer, cacheIndex, textureId );
378 textureInfo.loadState = TextureManager::NOT_STARTED;
381 // Check if we should add the observer.
382 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
383 switch( textureInfo.loadState )
385 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
386 case TextureManager::NOT_STARTED:
388 LoadTexture( textureInfo );
389 ObserveTexture( textureInfo, observer );
392 case TextureManager::LOADING:
394 ObserveTexture( textureInfo, observer );
397 case TextureManager::UPLOADED:
401 // The Texture has already loaded. The other observers have already been notified.
402 // We need to send a "late" loaded notification for this observer.
403 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
404 textureInfo.useAtlas, textureInfo.atlasRect,
405 textureInfo.preMultiplied );
409 case TextureManager::CANCELLED:
411 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
412 // (it's ref count has already been incremented, above)
413 textureInfo.loadState = TextureManager::LOADING;
414 ObserveTexture( textureInfo, observer );
417 case TextureManager::LOAD_FINISHED:
418 case TextureManager::WAITING_FOR_MASK:
419 // Loading has already completed. Do nothing.
423 // Return the TextureId for which this Texture can now be referenced by externally.
427 void TextureManager::Remove( const TextureManager::TextureId textureId )
429 int textureInfoIndex = GetCacheIndexFromId( textureId );
430 if( textureInfoIndex != INVALID_INDEX )
432 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
434 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
435 textureId, textureInfoIndex,
436 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
437 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
438 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
439 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
441 // Decrement the reference count and check if this is the last user of this Texture.
442 if( --textureInfo.referenceCount <= 0 )
444 // This is the last remove for this Texture.
445 textureInfo.referenceCount = 0;
446 bool removeTextureInfo = false;
448 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
449 if( textureInfo.loadState == UPLOADED )
451 if( textureInfo.atlas )
453 textureInfo.atlas.Remove( textureInfo.atlasRect );
455 removeTextureInfo = true;
457 else if( textureInfo.loadState == LOADING )
459 // We mark the textureInfo for removal.
460 // Once the load has completed, this method will be called again.
461 textureInfo.loadState = CANCELLED;
465 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
466 removeTextureInfo = true;
469 // If the state allows us to remove the TextureInfo data, we do so.
470 if( removeTextureInfo )
472 // Permanently remove the textureInfo struct.
473 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
479 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
481 VisualUrl visualUrl("");
482 int cacheIndex = GetCacheIndexFromId( textureId );
484 if( cacheIndex != INVALID_CACHE_INDEX )
486 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
487 cacheIndex, textureId );
489 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
490 visualUrl = cachedTextureInfo.url;
495 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
497 LoadState loadState = TextureManager::NOT_STARTED;
499 int cacheIndex = GetCacheIndexFromId( textureId );
500 if( cacheIndex != INVALID_CACHE_INDEX )
502 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
503 loadState = cachedTextureInfo.loadState;
507 for( auto&& elem : mExternalTextures )
509 if( elem.textureId == textureId )
511 loadState = LoadState::UPLOADED;
519 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
521 LoadState loadState = TextureManager::NOT_STARTED;
523 int cacheIndex = GetCacheIndexFromId( textureId );
524 if( cacheIndex != INVALID_CACHE_INDEX )
526 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
527 loadState = cachedTextureInfo.loadState;
533 TextureSet TextureManager::GetTextureSet( TextureId textureId )
535 TextureSet textureSet;// empty handle
537 int cacheIndex = GetCacheIndexFromId( textureId );
538 if( cacheIndex != INVALID_CACHE_INDEX )
540 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
541 textureSet = cachedTextureInfo.textureSet;
545 for( auto&& elem : mExternalTextures )
547 if( elem.textureId == textureId )
549 textureSet = elem.textureSet;
557 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
559 TextureManager::ExternalTextureInfo info;
560 info.textureId = GenerateUniqueTextureId();
561 info.textureSet = textureSet;
562 mExternalTextures.emplace_back( info );
563 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
566 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
568 if( url.size() > 0u )
570 // get the location from the Url
571 VisualUrl parseUrl( url );
572 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
574 std::string location = parseUrl.GetLocation();
575 if( location.size() > 0u )
577 TextureId id = std::stoi( location );
578 const auto end = mExternalTextures.end();
579 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
581 if( iter->textureId == id )
583 auto textureSet = iter->textureSet;
584 mExternalTextures.erase( iter );
595 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
597 // make sure an observer doesn't observe the same object twice
598 // otherwise it will get multiple calls to ObjectDestroyed()
599 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
600 mLifecycleObservers.PushBack( &observer );
603 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
605 // Find the observer...
606 auto endIter = mLifecycleObservers.End();
607 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
609 if( (*iter) == &observer)
611 mLifecycleObservers.Erase( iter );
615 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
619 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
623 if( textureInfo.loadState == NOT_STARTED )
625 textureInfo.loadState = LOADING;
627 if( !textureInfo.loadSynchronously )
629 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
630 auto loadingHelperIt = loadersContainer.GetNext();
631 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
632 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
633 textureInfo.desiredSize, textureInfo.fittingMode,
634 textureInfo.samplingMode, textureInfo.orientationCorrection );
641 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
642 TextureUploadObserver* observer )
646 textureInfo.observerList.PushBack( observer );
647 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
651 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
652 Devel::PixelBuffer pixelBuffer )
654 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
656 if( loadingContainer.size() >= 1u )
658 AsyncLoadingInfo loadingInfo = loadingContainer.front();
660 if( loadingInfo.loadId == id )
662 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
663 if( cacheIndex != INVALID_CACHE_INDEX )
665 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
667 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
669 if( textureInfo.loadState != CANCELLED )
671 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
672 PostLoad( textureInfo, pixelBuffer );
676 Remove( textureInfo.textureId );
681 loadingContainer.pop_front();
685 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
687 // Was the load successful?
688 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
690 // No atlas support for now
691 textureInfo.useAtlas = NO_ATLAS;
693 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
695 // If there is a mask texture ID associated with this texture, then apply the mask
696 // if it's already loaded. If it hasn't, and the mask is still loading,
697 // wait for the mask to finish loading.
698 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
700 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
701 if( maskLoadState == LOADING )
703 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
704 textureInfo.loadState = WAITING_FOR_MASK;
706 else if( maskLoadState == LOAD_FINISHED )
708 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
709 UploadTexture( pixelBuffer, textureInfo );
710 NotifyObservers( textureInfo, true );
715 UploadTexture( pixelBuffer, textureInfo );
716 NotifyObservers( textureInfo, true );
721 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
722 textureInfo.loadState = LOAD_FINISHED;
724 // Check if there was another texture waiting for this load to complete
725 // (e.g. if this was an image mask, and its load is on a different thread)
726 CheckForWaitingTexture( textureInfo );
731 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
732 // @todo If the load was unsuccessful, upload the broken image.
733 textureInfo.loadState = LOAD_FAILED;
734 CheckForWaitingTexture( textureInfo );
735 NotifyObservers( textureInfo, false );
739 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
741 // Search the cache, checking if any texture has this texture id as a
743 const unsigned int size = mTextureInfoContainer.size();
745 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
747 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
748 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
750 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
751 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
752 textureInfo.pixelBuffer.Reset();
754 if( maskTextureInfo.loadState == LOAD_FINISHED )
756 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
757 UploadTexture( pixelBuffer, textureInfo );
758 NotifyObservers( textureInfo, true );
762 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
763 textureInfo.loadState = LOAD_FAILED;
764 NotifyObservers( textureInfo, false );
770 void TextureManager::ApplyMask(
771 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
772 float contentScale, bool cropToMask )
774 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
775 if( maskCacheIndex != INVALID_CACHE_INDEX )
777 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
778 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
783 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
785 if( textureInfo.useAtlas != USE_ATLAS )
787 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
789 // If the texture doesn't have an alpha channel, can't pre-multiply it.
790 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
791 // the status for use in the observer.
792 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
793 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
794 PreMultiply( pixelBuffer, preMultiply );
795 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
797 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
798 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
800 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
801 texture.Upload( pixelData );
802 if ( ! textureInfo.textureSet )
804 textureInfo.textureSet = TextureSet::New();
806 textureInfo.textureSet.SetTexture( 0u, texture );
809 // Update the load state.
810 // Note: This is regardless of success as we care about whether a
811 // load attempt is in progress or not. If unsuccessful, a broken
812 // image is still loaded.
813 textureInfo.loadState = UPLOADED;
816 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
818 TextureId textureId = textureInfo.textureId;
820 // If there is an observer: Notify the load is complete, whether successful or not,
821 // and erase it from the list
822 unsigned int observerCount = textureInfo.observerList.Count();
823 TextureInfo* info = &textureInfo;
825 while( observerCount )
827 TextureUploadObserver* observer = info->observerList[0];
829 // During UploadComplete() a Control ResourceReady() signal is emitted.
830 // During that signal the app may add remove /add Textures (e.g. via
831 // ImageViews). At this point no more observers can be added to the
832 // observerList, because textureInfo.loadState = UPLOADED. However it is
833 // possible for observers to be removed, hence we check the observer list
834 // count every iteration.
836 // The reference to the textureInfo struct can also become invalidated,
837 // because new load requests can modify the mTextureInfoContainer list
838 // (e.g. if more requests are pushed back it can cause the list to be
839 // resized invalidating the reference to the TextureInfo ).
840 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
841 info->preMultiplied );
842 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
844 // Get the textureInfo from the container again as it may have been
847 int textureInfoIndex = GetCacheIndexFromId( textureId );
848 if( textureInfoIndex == INVALID_CACHE_INDEX)
850 return; // texture has been removed - can stop.
853 info = &mTextureInfoContainer[ textureInfoIndex ];
854 observerCount = info->observerList.Count();
855 if ( observerCount > 0 )
857 // remove the observer that was just triggered if it's still in the list
858 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
862 info->observerList.Erase( j );
871 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
873 return mCurrentTextureId++;
876 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
878 const unsigned int size = mTextureInfoContainer.size();
880 for( unsigned int i = 0; i < size; ++i )
882 if( mTextureInfoContainer[i].textureId == textureId )
888 return INVALID_CACHE_INDEX;
891 TextureManager::TextureHash TextureManager::GenerateHash(
892 const std::string& url,
893 const ImageDimensions size,
894 const FittingMode::Type fittingMode,
895 const Dali::SamplingMode::Type samplingMode,
896 const UseAtlas useAtlas,
897 TextureId maskTextureId,
898 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
900 std::string hashTarget( url );
901 const size_t urlLength = hashTarget.length();
902 const uint16_t width = size.GetWidth();
903 const uint16_t height = size.GetWidth();
905 // If either the width or height has been specified, include the resizing options in the hash
906 if( width != 0 || height != 0 )
908 // We are appending 5 bytes to the URL to form the hash input.
909 hashTarget.resize( urlLength + 5u );
910 char* hashTargetPtr = &( hashTarget[ urlLength ] );
912 // Pack the width and height (4 bytes total).
913 *hashTargetPtr++ = size.GetWidth() & 0xff;
914 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
915 *hashTargetPtr++ = size.GetHeight() & 0xff;
916 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
918 // Bit-pack the FittingMode, SamplingMode and atlasing.
919 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
920 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
924 // We are not including sizing information, but we still need an extra byte for atlasing.
925 hashTarget.resize( urlLength + 1u );
926 // Add the atlasing to the hash input.
927 hashTarget[ urlLength ] = useAtlas;
930 if( maskTextureId != INVALID_TEXTURE_ID )
932 auto textureIdIndex = hashTarget.length();
933 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
934 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
936 // Append the texture id to the end of the URL byte by byte:
937 // (to avoid SIGBUS / alignment issues)
938 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
940 *hashTargetPtr++ = maskTextureId & 0xff;
941 maskTextureId >>= 8u;
945 auto premultipliedIndex = hashTarget.length();
946 hashTarget.resize( premultipliedIndex + 1 );
947 switch( preMultiplyOnLoad )
949 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
951 hashTarget[ premultipliedIndex ] = 't';
954 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
956 hashTarget[ premultipliedIndex ] = 'f';
961 return Dali::CalculateHash( hashTarget );
964 int TextureManager::FindCachedTexture(
965 const TextureManager::TextureHash hash,
966 const std::string& url,
967 const ImageDimensions size,
968 const FittingMode::Type fittingMode,
969 const Dali::SamplingMode::Type samplingMode,
971 TextureId maskTextureId,
972 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
974 // Default to an invalid ID, in case we do not find a match.
975 int cacheIndex = INVALID_CACHE_INDEX;
977 // Iterate through our hashes to find a match.
978 const unsigned int count = mTextureInfoContainer.size();
979 for( unsigned int i = 0u; i < count; ++i )
981 if( mTextureInfoContainer[i].hash == hash )
983 // We have a match, now we check all the original parameters in case of a hash collision.
984 TextureInfo& textureInfo( mTextureInfoContainer[i] );
985 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
986 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
988 if( ( url == textureInfo.url.GetUrl() ) &&
989 ( useAtlas == textureInfo.useAtlas ) &&
990 ( maskTextureId == textureInfo.maskTextureId ) &&
991 ( size == textureInfo.desiredSize ) &&
992 ( preMultiplyOnLoad == multiplyOnLoad ) &&
993 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
994 ( fittingMode == textureInfo.fittingMode &&
995 samplingMode == textureInfo.samplingMode ) ) )
997 // The found Texture is a match.
1007 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1009 const unsigned int count = mTextureInfoContainer.size();
1010 for( unsigned int i = 0; i < count; ++i )
1012 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1013 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1014 j != textureInfo.observerList.End(); )
1016 if( *j == observer )
1018 j = textureInfo.observerList.Erase( j );
1029 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1030 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1031 AsyncLoadingInfoContainerType())
1035 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1036 const VisualUrl& url,
1037 ImageDimensions desiredSize,
1038 FittingMode::Type fittingMode,
1039 SamplingMode::Type samplingMode,
1040 bool orientationCorrection)
1042 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1043 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1044 mLoadingInfoContainer.back().loadId = id;
1047 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1048 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1052 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1053 Toolkit::AsyncImageLoader loader,
1054 TextureManager& textureManager,
1055 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1057 mTextureManager(textureManager),
1058 mLoadingInfoContainer(std::move(loadingInfoContainer))
1060 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1061 this, &AsyncLoadingHelper::AsyncLoadComplete);
1064 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1065 Devel::PixelBuffer pixelBuffer)
1067 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1070 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1072 mBrokenImageUrl = brokenImageUrl;
1075 } // namespace Internal
1077 } // namespace Toolkit