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 char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png" ); ///< URL For the broken image placeholder
87 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
88 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
91 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
93 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
95 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
97 pixelBuffer.MultiplyColorByAlpha();
102 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
106 } // Anonymous namespace
108 TextureManager::MaskingData::MaskingData()
110 mAlphaMaskId( INVALID_TEXTURE_ID ),
111 mContentScaleFactor( 1.0f ),
116 TextureManager::TextureManager()
117 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
118 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
121 mCurrentTextureId( 0 ),
122 mQueueLoadFlag(false)
126 TextureSet TextureManager::LoadTexture(
127 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
128 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
129 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
130 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
131 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
132 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
133 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
135 TextureSet textureSet;
137 loadingStatus = false;
138 textureRect = FULL_ATLAS_RECT;
140 if( VisualUrl::TEXTURE == url.GetProtocolType())
142 std::string location = url.GetLocation();
143 if( location.size() > 0u )
145 TextureId id = std::stoi( location );
146 for( auto&& elem : mExternalTextures )
148 if( elem.textureId == id )
150 textureId = elem.textureId;
151 return elem.textureSet;
156 else if( synchronousLoading )
161 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
162 orientationCorrection );
165 PreMultiply( pixelBuffer, preMultiplyOnLoad );
166 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
172 textureSet = TextureSet::New();
173 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
176 PreMultiply( pixelBuffer, preMultiplyOnLoad );
177 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
179 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
180 data.GetWidth(), data.GetHeight() );
181 texture.Upload( data );
182 textureSet = TextureSet::New();
183 textureSet.SetTexture( 0u, texture );
187 if( atlasingStatus ) // attempt atlasing
189 textureSet = imageAtlasManager->Add( textureRect, data );
191 if( !textureSet ) // big image, no atlasing or atlasing failed
193 atlasingStatus = false;
194 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
195 data.GetWidth(), data.GetHeight() );
196 texture.Upload( data );
197 textureSet = TextureSet::New();
198 textureSet.SetTexture( 0u, texture );
204 loadingStatus = true;
207 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
209 if( !textureSet ) // big image, no atlasing or atlasing failed
211 atlasingStatus = false;
214 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
215 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
219 textureId = RequestLoad( url,
220 maskInfo->mAlphaMaskId,
221 maskInfo->mContentScaleFactor,
223 fittingMode, samplingMode,
224 TextureManager::NO_ATLAS,
225 maskInfo->mCropToMask,
227 orientationCorrection,
228 reloadPolicy, preMultiplyOnLoad );
231 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
234 case TextureManager::NOT_STARTED:
235 case TextureManager::LOADING:
236 case TextureManager::LOAD_FAILED:
238 loadingStatus = true;
243 loadingStatus = false;
248 if( loadState == TextureManager::UPLOADED )
250 // UploadComplete has already been called - keep the same texture set
251 textureSet = GetTextureSet( textureId );
256 if( ! atlasingStatus && textureSet )
258 Sampler sampler = Sampler::New();
259 sampler.SetWrapMode( wrapModeU, wrapModeV );
260 textureSet.SetSampler( 0u, sampler );
266 TextureManager::TextureId TextureManager::RequestLoad(
267 const VisualUrl& url,
268 const ImageDimensions desiredSize,
269 FittingMode::Type fittingMode,
270 Dali::SamplingMode::Type samplingMode,
271 const UseAtlas useAtlas,
272 TextureUploadObserver* observer,
273 bool orientationCorrection,
274 TextureManager::ReloadPolicy reloadPolicy,
275 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
277 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
278 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
282 TextureManager::TextureId TextureManager::RequestLoad(
283 const VisualUrl& url,
284 TextureId maskTextureId,
286 const ImageDimensions desiredSize,
287 FittingMode::Type fittingMode,
288 Dali::SamplingMode::Type samplingMode,
289 const UseAtlas useAtlas,
291 TextureUploadObserver* observer,
292 bool orientationCorrection,
293 TextureManager::ReloadPolicy reloadPolicy,
294 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
296 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
297 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
301 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
303 // Use the normal load procedure to get the alpha mask.
304 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
305 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
306 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
307 TextureManager::ReloadPolicy::CACHED, preMultiply );
310 TextureManager::TextureId TextureManager::RequestLoadInternal(
311 const VisualUrl& url,
312 TextureId maskTextureId,
314 const ImageDimensions desiredSize,
315 FittingMode::Type fittingMode,
316 Dali::SamplingMode::Type samplingMode,
319 StorageType storageType,
320 TextureUploadObserver* observer,
321 bool orientationCorrection,
322 TextureManager::ReloadPolicy reloadPolicy,
323 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
325 // First check if the requested Texture is cached.
326 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
327 maskTextureId, preMultiplyOnLoad );
329 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
331 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
332 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
333 maskTextureId, preMultiplyOnLoad );
335 // Check if the requested Texture exists in the cache.
336 if( cacheIndex != INVALID_CACHE_INDEX )
338 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
340 // Mark this texture being used by another client resource. Forced reload would replace the current texture
341 // without the need for incrementing the reference count.
342 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
344 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
345 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
346 url.GetUrl().c_str(), observer, cacheIndex, textureId );
349 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
351 // We need a new Texture.
352 textureId = GenerateUniqueTextureId();
353 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
354 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
355 desiredSize, contentScale, fittingMode, samplingMode,
356 false, cropToMask, useAtlas, textureHash, orientationCorrection,
358 cacheIndex = mTextureInfoContainer.size() - 1u;
360 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
361 url.GetUrl().c_str(), observer, cacheIndex, textureId );
364 // The below code path is common whether we are using the cache or not.
365 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
366 // or a new TextureInfo just created.
367 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
368 textureInfo.maskTextureId = maskTextureId;
369 textureInfo.storageType = storageType;
370 textureInfo.orientationCorrection = orientationCorrection;
372 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
373 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
374 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
375 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
376 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
378 // Force reloading of texture by setting loadState unless already loading or cancelled.
379 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
380 TextureManager::CANCELLED != textureInfo.loadState )
382 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
383 url.GetUrl().c_str(), observer, cacheIndex, textureId );
384 textureInfo.loadState = TextureManager::NOT_STARTED;
387 // Check if we should add the observer.
388 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
389 switch( textureInfo.loadState )
391 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
392 case TextureManager::NOT_STARTED:
394 LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
397 case TextureManager::LOADING:
399 ObserveTexture( textureInfo, observer );
402 case TextureManager::UPLOADED:
406 // The Texture has already loaded. The other observers have already been notified.
407 // We need to send a "late" loaded notification for this observer.
408 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
409 textureInfo.useAtlas, textureInfo.atlasRect,
410 textureInfo.preMultiplied );
414 case TextureManager::CANCELLED:
416 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
417 // (it's ref count has already been incremented, above)
418 textureInfo.loadState = TextureManager::LOADING;
419 ObserveTexture( textureInfo, observer );
422 case TextureManager::LOAD_FINISHED:
423 case TextureManager::WAITING_FOR_MASK:
424 // Loading has already completed. Do nothing.
428 // Return the TextureId for which this Texture can now be referenced by externally.
432 void TextureManager::Remove( const TextureManager::TextureId textureId )
434 int textureInfoIndex = GetCacheIndexFromId( textureId );
435 if( textureInfoIndex != INVALID_INDEX )
437 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
439 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
440 textureId, textureInfoIndex,
441 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
442 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
443 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
444 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
446 // Decrement the reference count and check if this is the last user of this Texture.
447 if( --textureInfo.referenceCount <= 0 )
449 // This is the last remove for this Texture.
450 textureInfo.referenceCount = 0;
451 bool removeTextureInfo = false;
453 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
454 if( textureInfo.loadState == UPLOADED )
456 if( textureInfo.atlas )
458 textureInfo.atlas.Remove( textureInfo.atlasRect );
460 removeTextureInfo = true;
462 else if( textureInfo.loadState == LOADING )
464 // We mark the textureInfo for removal.
465 // Once the load has completed, this method will be called again.
466 textureInfo.loadState = CANCELLED;
470 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
471 removeTextureInfo = true;
474 // If the state allows us to remove the TextureInfo data, we do so.
475 if( removeTextureInfo )
477 // Permanently remove the textureInfo struct.
478 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
484 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
486 int cacheIndex = GetCacheIndexFromId( textureId );
487 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
489 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
490 return cachedTextureInfo.url;
493 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
495 LoadState loadState = TextureManager::NOT_STARTED;
497 int cacheIndex = GetCacheIndexFromId( textureId );
498 if( cacheIndex != INVALID_CACHE_INDEX )
500 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
501 loadState = cachedTextureInfo.loadState;
505 for( auto&& elem : mExternalTextures )
507 if( elem.textureId == textureId )
509 loadState = LoadState::UPLOADED;
517 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
519 LoadState loadState = TextureManager::NOT_STARTED;
521 int cacheIndex = GetCacheIndexFromId( textureId );
522 if( cacheIndex != INVALID_CACHE_INDEX )
524 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
525 loadState = cachedTextureInfo.loadState;
531 TextureSet TextureManager::GetTextureSet( TextureId textureId )
533 TextureSet textureSet;// empty handle
535 int cacheIndex = GetCacheIndexFromId( textureId );
536 if( cacheIndex != INVALID_CACHE_INDEX )
538 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
539 textureSet = cachedTextureInfo.textureSet;
543 for( auto&& elem : mExternalTextures )
545 if( elem.textureId == textureId )
547 textureSet = elem.textureSet;
555 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
557 TextureManager::ExternalTextureInfo info;
558 info.textureId = GenerateUniqueTextureId();
559 info.textureSet = textureSet;
560 mExternalTextures.emplace_back( info );
561 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
564 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
566 if( url.size() > 0u )
568 // get the location from the Url
569 VisualUrl parseUrl( url );
570 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
572 std::string location = parseUrl.GetLocation();
573 if( location.size() > 0u )
575 TextureId id = std::stoi( location );
576 const auto end = mExternalTextures.end();
577 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
579 if( iter->textureId == id )
581 auto textureSet = iter->textureSet;
582 mExternalTextures.erase( iter );
592 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
594 switch( textureInfo.loadState )
601 QueueLoadTexture( textureInfo, observer );
605 LoadTexture( textureInfo, observer );
613 case WAITING_FOR_MASK:
620 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
622 auto textureId = textureInfo.textureId;
623 mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
626 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
628 textureInfo.loadState = LOADING;
629 if( !textureInfo.loadSynchronously )
631 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
632 auto loadingHelperIt = loadersContainer.GetNext();
633 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
634 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
635 textureInfo.desiredSize, textureInfo.fittingMode,
636 textureInfo.samplingMode, textureInfo.orientationCorrection );
638 ObserveTexture( textureInfo, observer );
641 void TextureManager::ProcessQueuedTextures()
643 for( auto&& element : mLoadQueue )
645 int cacheIndex = GetCacheIndexFromId( element.mTextureId );
646 if( cacheIndex != INVALID_CACHE_INDEX )
648 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
649 LoadTexture( textureInfo, element.mObserver );
655 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
656 TextureUploadObserver* observer )
660 textureInfo.observerList.PushBack( observer );
661 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
665 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
666 Devel::PixelBuffer pixelBuffer )
668 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
670 if( loadingContainer.size() >= 1u )
672 AsyncLoadingInfo loadingInfo = loadingContainer.front();
674 if( loadingInfo.loadId == id )
676 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
677 if( cacheIndex != INVALID_CACHE_INDEX )
679 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
681 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
683 if( textureInfo.loadState != CANCELLED )
685 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
686 PostLoad( textureInfo, pixelBuffer );
690 Remove( textureInfo.textureId );
695 loadingContainer.pop_front();
699 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
701 // Was the load successful?
702 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
704 // No atlas support for now
705 textureInfo.useAtlas = NO_ATLAS;
707 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
709 // If there is a mask texture ID associated with this texture, then apply the mask
710 // if it's already loaded. If it hasn't, and the mask is still loading,
711 // wait for the mask to finish loading.
712 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
714 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
715 if( maskLoadState == LOADING )
717 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
718 textureInfo.loadState = WAITING_FOR_MASK;
720 else if( maskLoadState == LOAD_FINISHED )
722 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
723 UploadTexture( pixelBuffer, textureInfo );
724 NotifyObservers( textureInfo, true );
729 UploadTexture( pixelBuffer, textureInfo );
730 NotifyObservers( textureInfo, true );
735 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
736 textureInfo.loadState = LOAD_FINISHED;
738 // Check if there was another texture waiting for this load to complete
739 // (e.g. if this was an image mask, and its load is on a different thread)
740 CheckForWaitingTexture( textureInfo );
745 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
746 // @todo If the load was unsuccessful, upload the broken image.
747 textureInfo.loadState = LOAD_FAILED;
748 CheckForWaitingTexture( textureInfo );
749 NotifyObservers( textureInfo, false );
753 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
755 // Search the cache, checking if any texture has this texture id as a
757 const unsigned int size = mTextureInfoContainer.size();
759 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
761 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
762 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
764 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
765 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
766 textureInfo.pixelBuffer.Reset();
768 if( maskTextureInfo.loadState == LOAD_FINISHED )
770 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
771 UploadTexture( pixelBuffer, textureInfo );
772 NotifyObservers( textureInfo, true );
776 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
777 textureInfo.loadState = LOAD_FAILED;
778 NotifyObservers( textureInfo, false );
784 void TextureManager::ApplyMask(
785 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
786 float contentScale, bool cropToMask )
788 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
789 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
790 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
793 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
795 if( textureInfo.useAtlas != USE_ATLAS )
797 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
799 // If the texture doesn't have an alpha channel, can't pre-multiply it.
800 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
801 // the status for use in the observer.
802 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
803 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
804 PreMultiply( pixelBuffer, preMultiply );
805 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
807 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
808 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
810 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
811 texture.Upload( pixelData );
812 if ( ! textureInfo.textureSet )
814 textureInfo.textureSet = TextureSet::New();
816 textureInfo.textureSet.SetTexture( 0u, texture );
819 // Update the load state.
820 // Note: This is regardless of success as we care about whether a
821 // load attempt is in progress or not. If unsuccessful, a broken
822 // image is still loaded.
823 textureInfo.loadState = UPLOADED;
826 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
828 TextureId textureId = textureInfo.textureId;
830 // If there is an observer: Notify the load is complete, whether successful or not,
831 // and erase it from the list
832 TextureInfo* info = &textureInfo;
834 mQueueLoadFlag = true;
836 while( info->observerList.Count() )
838 TextureUploadObserver* observer = info->observerList[0];
840 // During UploadComplete() a Control ResourceReady() signal is emitted.
841 // During that signal the app may add remove /add Textures (e.g. via
843 // It is possible for observers to be removed from the observer list,
844 // and it is also possible for the mTextureInfoContainer to be modified,
845 // invalidating the reference to the textureInfo struct.
846 // Texture load requests for the same URL are deferred until the end of this
848 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
849 info->preMultiplied );
850 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
852 // Get the textureInfo from the container again as it may have been invalidated.
853 int textureInfoIndex = GetCacheIndexFromId( textureId );
854 if( textureInfoIndex == INVALID_CACHE_INDEX)
856 mQueueLoadFlag = false;
857 ProcessQueuedTextures();
858 return; // texture has been removed - can stop.
860 info = &mTextureInfoContainer[ textureInfoIndex ];
862 // remove the observer that was just triggered if it's still in the list
863 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
867 info->observerList.Erase( j );
873 mQueueLoadFlag = false;
874 ProcessQueuedTextures();
877 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
879 return mCurrentTextureId++;
882 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
884 const unsigned int size = mTextureInfoContainer.size();
886 for( unsigned int i = 0; i < size; ++i )
888 if( mTextureInfoContainer[i].textureId == textureId )
894 return INVALID_CACHE_INDEX;
897 TextureManager::TextureHash TextureManager::GenerateHash(
898 const std::string& url,
899 const ImageDimensions size,
900 const FittingMode::Type fittingMode,
901 const Dali::SamplingMode::Type samplingMode,
902 const UseAtlas useAtlas,
903 TextureId maskTextureId,
904 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
906 std::string hashTarget( url );
907 const size_t urlLength = hashTarget.length();
908 const uint16_t width = size.GetWidth();
909 const uint16_t height = size.GetWidth();
911 // If either the width or height has been specified, include the resizing options in the hash
912 if( width != 0 || height != 0 )
914 // We are appending 5 bytes to the URL to form the hash input.
915 hashTarget.resize( urlLength + 5u );
916 char* hashTargetPtr = &( hashTarget[ urlLength ] );
918 // Pack the width and height (4 bytes total).
919 *hashTargetPtr++ = size.GetWidth() & 0xff;
920 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
921 *hashTargetPtr++ = size.GetHeight() & 0xff;
922 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
924 // Bit-pack the FittingMode, SamplingMode and atlasing.
925 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
926 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
930 // We are not including sizing information, but we still need an extra byte for atlasing.
931 hashTarget.resize( urlLength + 1u );
932 // Add the atlasing to the hash input.
933 hashTarget[ urlLength ] = useAtlas;
936 if( maskTextureId != INVALID_TEXTURE_ID )
938 auto textureIdIndex = hashTarget.length();
939 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
940 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
942 // Append the texture id to the end of the URL byte by byte:
943 // (to avoid SIGBUS / alignment issues)
944 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
946 *hashTargetPtr++ = maskTextureId & 0xff;
947 maskTextureId >>= 8u;
951 auto premultipliedIndex = hashTarget.length();
952 hashTarget.resize( premultipliedIndex + 1 );
953 switch( preMultiplyOnLoad )
955 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
957 hashTarget[ premultipliedIndex ] = 't';
960 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
962 hashTarget[ premultipliedIndex ] = 'f';
967 return Dali::CalculateHash( hashTarget );
970 int TextureManager::FindCachedTexture(
971 const TextureManager::TextureHash hash,
972 const std::string& url,
973 const ImageDimensions size,
974 const FittingMode::Type fittingMode,
975 const Dali::SamplingMode::Type samplingMode,
977 TextureId maskTextureId,
978 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
980 // Default to an invalid ID, in case we do not find a match.
981 int cacheIndex = INVALID_CACHE_INDEX;
983 // Iterate through our hashes to find a match.
984 const unsigned int count = mTextureInfoContainer.size();
985 for( unsigned int i = 0u; i < count; ++i )
987 if( mTextureInfoContainer[i].hash == hash )
989 // We have a match, now we check all the original parameters in case of a hash collision.
990 TextureInfo& textureInfo( mTextureInfoContainer[i] );
991 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
992 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
994 if( ( url == textureInfo.url.GetUrl() ) &&
995 ( useAtlas == textureInfo.useAtlas ) &&
996 ( maskTextureId == textureInfo.maskTextureId ) &&
997 ( size == textureInfo.desiredSize ) &&
998 ( preMultiplyOnLoad == multiplyOnLoad ) &&
999 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1000 ( fittingMode == textureInfo.fittingMode &&
1001 samplingMode == textureInfo.samplingMode ) ) )
1003 // The found Texture is a match.
1013 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1015 const unsigned int count = mTextureInfoContainer.size();
1016 for( unsigned int i = 0; i < count; ++i )
1018 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1019 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1020 j != textureInfo.observerList.End(); )
1022 if( *j == observer )
1024 j = textureInfo.observerList.Erase( j );
1035 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1036 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1037 AsyncLoadingInfoContainerType())
1041 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1042 const VisualUrl& url,
1043 ImageDimensions desiredSize,
1044 FittingMode::Type fittingMode,
1045 SamplingMode::Type samplingMode,
1046 bool orientationCorrection)
1048 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1049 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1050 mLoadingInfoContainer.back().loadId = id;
1053 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1054 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1058 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1059 Toolkit::AsyncImageLoader loader,
1060 TextureManager& textureManager,
1061 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1063 mTextureManager(textureManager),
1064 mLoadingInfoContainer(std::move(loadingInfoContainer))
1066 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1067 this, &AsyncLoadingHelper::AsyncLoadComplete);
1070 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1071 Devel::PixelBuffer pixelBuffer)
1073 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1076 } // namespace Internal
1078 } // namespace Toolkit