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 );
232 loadingStatus = ( loadState == TextureManager::LOADING );
234 if( loadState == TextureManager::UPLOADED )
236 // UploadComplete has already been called - keep the same texture set
237 textureSet = GetTextureSet( textureId );
242 if( ! atlasingStatus && textureSet )
244 Sampler sampler = Sampler::New();
245 sampler.SetWrapMode( wrapModeU, wrapModeV );
246 textureSet.SetSampler( 0u, sampler );
252 TextureManager::TextureId TextureManager::RequestLoad(
253 const VisualUrl& url,
254 const ImageDimensions desiredSize,
255 FittingMode::Type fittingMode,
256 Dali::SamplingMode::Type samplingMode,
257 const UseAtlas useAtlas,
258 TextureUploadObserver* observer,
259 bool orientationCorrection,
260 TextureManager::ReloadPolicy reloadPolicy,
261 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
263 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
264 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
268 TextureManager::TextureId TextureManager::RequestLoad(
269 const VisualUrl& url,
270 TextureId maskTextureId,
272 const ImageDimensions desiredSize,
273 FittingMode::Type fittingMode,
274 Dali::SamplingMode::Type samplingMode,
275 const UseAtlas useAtlas,
277 TextureUploadObserver* observer,
278 bool orientationCorrection,
279 TextureManager::ReloadPolicy reloadPolicy,
280 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
282 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
283 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
287 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
289 // Use the normal load procedure to get the alpha mask.
290 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
291 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
292 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
293 TextureManager::ReloadPolicy::CACHED, preMultiply );
296 TextureManager::TextureId TextureManager::RequestLoadInternal(
297 const VisualUrl& url,
298 TextureId maskTextureId,
300 const ImageDimensions desiredSize,
301 FittingMode::Type fittingMode,
302 Dali::SamplingMode::Type samplingMode,
305 StorageType storageType,
306 TextureUploadObserver* observer,
307 bool orientationCorrection,
308 TextureManager::ReloadPolicy reloadPolicy,
309 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
311 // First check if the requested Texture is cached.
312 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
313 maskTextureId, preMultiplyOnLoad );
315 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
317 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
318 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
319 maskTextureId, preMultiplyOnLoad );
321 // Check if the requested Texture exists in the cache.
322 if( cacheIndex != INVALID_CACHE_INDEX )
324 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
326 // Mark this texture being used by another client resource. Forced reload would replace the current texture
327 // without the need for incrementing the reference count.
328 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
330 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
331 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
332 url.GetUrl().c_str(), observer, cacheIndex, textureId );
335 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
337 // We need a new Texture.
338 textureId = GenerateUniqueTextureId();
339 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
340 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
341 desiredSize, contentScale, fittingMode, samplingMode,
342 false, cropToMask, useAtlas, textureHash, orientationCorrection,
344 cacheIndex = mTextureInfoContainer.size() - 1u;
346 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
347 url.GetUrl().c_str(), observer, cacheIndex, textureId );
350 // The below code path is common whether we are using the cache or not.
351 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
352 // or a new TextureInfo just created.
353 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
354 textureInfo.maskTextureId = maskTextureId;
355 textureInfo.storageType = storageType;
356 textureInfo.orientationCorrection = orientationCorrection;
358 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
359 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
360 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
361 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
362 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
364 // Force reloading of texture by setting loadState unless already loading or cancelled.
365 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
366 TextureManager::CANCELLED != textureInfo.loadState )
368 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
369 url.GetUrl().c_str(), observer, cacheIndex, textureId );
370 textureInfo.loadState = TextureManager::NOT_STARTED;
373 // Check if we should add the observer.
374 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
375 switch( textureInfo.loadState )
377 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
378 case TextureManager::NOT_STARTED:
380 LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
383 case TextureManager::LOADING:
385 ObserveTexture( textureInfo, observer );
388 case TextureManager::UPLOADED:
392 // The Texture has already loaded. The other observers have already been notified.
393 // We need to send a "late" loaded notification for this observer.
394 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
395 textureInfo.useAtlas, textureInfo.atlasRect,
396 textureInfo.preMultiplied );
400 case TextureManager::CANCELLED:
402 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
403 // (it's ref count has already been incremented, above)
404 textureInfo.loadState = TextureManager::LOADING;
405 ObserveTexture( textureInfo, observer );
408 case TextureManager::LOAD_FINISHED:
409 case TextureManager::WAITING_FOR_MASK:
410 // Loading has already completed. Do nothing.
414 // Return the TextureId for which this Texture can now be referenced by externally.
418 void TextureManager::Remove( const TextureManager::TextureId textureId )
420 int textureInfoIndex = GetCacheIndexFromId( textureId );
421 if( textureInfoIndex != INVALID_INDEX )
423 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
425 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
426 textureId, textureInfoIndex,
427 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
428 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
429 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
430 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
432 // Decrement the reference count and check if this is the last user of this Texture.
433 if( --textureInfo.referenceCount <= 0 )
435 // This is the last remove for this Texture.
436 textureInfo.referenceCount = 0;
437 bool removeTextureInfo = false;
439 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
440 if( textureInfo.loadState == UPLOADED )
442 if( textureInfo.atlas )
444 textureInfo.atlas.Remove( textureInfo.atlasRect );
446 removeTextureInfo = true;
448 else if( textureInfo.loadState == LOADING )
450 // We mark the textureInfo for removal.
451 // Once the load has completed, this method will be called again.
452 textureInfo.loadState = CANCELLED;
456 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
457 removeTextureInfo = true;
460 // If the state allows us to remove the TextureInfo data, we do so.
461 if( removeTextureInfo )
463 // Permanently remove the textureInfo struct.
464 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
470 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
472 int cacheIndex = GetCacheIndexFromId( textureId );
473 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
475 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
476 return cachedTextureInfo.url;
479 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
481 LoadState loadState = TextureManager::NOT_STARTED;
483 int cacheIndex = GetCacheIndexFromId( textureId );
484 if( cacheIndex != INVALID_CACHE_INDEX )
486 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
487 loadState = cachedTextureInfo.loadState;
491 for( auto&& elem : mExternalTextures )
493 if( elem.textureId == textureId )
495 loadState = LoadState::UPLOADED;
503 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
505 LoadState loadState = TextureManager::NOT_STARTED;
507 int cacheIndex = GetCacheIndexFromId( textureId );
508 if( cacheIndex != INVALID_CACHE_INDEX )
510 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
511 loadState = cachedTextureInfo.loadState;
517 TextureSet TextureManager::GetTextureSet( TextureId textureId )
519 TextureSet textureSet;// empty handle
521 int cacheIndex = GetCacheIndexFromId( textureId );
522 if( cacheIndex != INVALID_CACHE_INDEX )
524 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
525 textureSet = cachedTextureInfo.textureSet;
529 for( auto&& elem : mExternalTextures )
531 if( elem.textureId == textureId )
533 textureSet = elem.textureSet;
541 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
543 TextureManager::ExternalTextureInfo info;
544 info.textureId = GenerateUniqueTextureId();
545 info.textureSet = textureSet;
546 mExternalTextures.emplace_back( info );
547 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
550 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
552 if( url.size() > 0u )
554 // get the location from the Url
555 VisualUrl parseUrl( url );
556 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
558 std::string location = parseUrl.GetLocation();
559 if( location.size() > 0u )
561 TextureId id = std::stoi( location );
562 const auto end = mExternalTextures.end();
563 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
565 if( iter->textureId == id )
567 auto textureSet = iter->textureSet;
568 mExternalTextures.erase( iter );
578 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
580 switch( textureInfo.loadState )
587 QueueLoadTexture( textureInfo, observer );
591 LoadTexture( textureInfo, observer );
599 case WAITING_FOR_MASK:
606 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
608 auto textureId = textureInfo.textureId;
609 mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
612 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
614 textureInfo.loadState = LOADING;
615 if( !textureInfo.loadSynchronously )
617 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
618 auto loadingHelperIt = loadersContainer.GetNext();
619 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
620 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
621 textureInfo.desiredSize, textureInfo.fittingMode,
622 textureInfo.samplingMode, textureInfo.orientationCorrection );
624 ObserveTexture( textureInfo, observer );
627 void TextureManager::ProcessQueuedTextures()
629 for( auto&& element : mLoadQueue )
631 int cacheIndex = GetCacheIndexFromId( element.mTextureId );
632 if( cacheIndex != INVALID_CACHE_INDEX )
634 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
635 LoadTexture( textureInfo, element.mObserver );
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 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
776 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
779 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
781 if( textureInfo.useAtlas != USE_ATLAS )
783 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
785 // If the texture doesn't have an alpha channel, can't pre-multiply it.
786 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
787 // the status for use in the observer.
788 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
789 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
790 PreMultiply( pixelBuffer, preMultiply );
791 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
793 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
794 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
796 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
797 texture.Upload( pixelData );
798 if ( ! textureInfo.textureSet )
800 textureInfo.textureSet = TextureSet::New();
802 textureInfo.textureSet.SetTexture( 0u, texture );
805 // Update the load state.
806 // Note: This is regardless of success as we care about whether a
807 // load attempt is in progress or not. If unsuccessful, a broken
808 // image is still loaded.
809 textureInfo.loadState = UPLOADED;
812 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
814 TextureId textureId = textureInfo.textureId;
816 // If there is an observer: Notify the load is complete, whether successful or not,
817 // and erase it from the list
818 TextureInfo* info = &textureInfo;
820 mQueueLoadFlag = true;
822 while( info->observerList.Count() )
824 TextureUploadObserver* observer = info->observerList[0];
826 // During UploadComplete() a Control ResourceReady() signal is emitted.
827 // During that signal the app may add remove /add Textures (e.g. via
829 // It is possible for observers to be removed from the observer list,
830 // and it is also possible for the mTextureInfoContainer to be modified,
831 // invalidating the reference to the textureInfo struct.
832 // Texture load requests for the same URL are deferred until the end of this
834 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
835 info->preMultiplied );
836 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
838 // Get the textureInfo from the container again as it may have been invalidated.
839 int textureInfoIndex = GetCacheIndexFromId( textureId );
840 if( textureInfoIndex == INVALID_CACHE_INDEX)
842 mQueueLoadFlag = false;
843 ProcessQueuedTextures();
844 return; // texture has been removed - can stop.
846 info = &mTextureInfoContainer[ textureInfoIndex ];
848 // remove the observer that was just triggered if it's still in the list
849 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
853 info->observerList.Erase( j );
859 mQueueLoadFlag = false;
860 ProcessQueuedTextures();
863 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
865 return mCurrentTextureId++;
868 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
870 const unsigned int size = mTextureInfoContainer.size();
872 for( unsigned int i = 0; i < size; ++i )
874 if( mTextureInfoContainer[i].textureId == textureId )
880 return INVALID_CACHE_INDEX;
883 TextureManager::TextureHash TextureManager::GenerateHash(
884 const std::string& url,
885 const ImageDimensions size,
886 const FittingMode::Type fittingMode,
887 const Dali::SamplingMode::Type samplingMode,
888 const UseAtlas useAtlas,
889 TextureId maskTextureId,
890 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
892 std::string hashTarget( url );
893 const size_t urlLength = hashTarget.length();
894 const uint16_t width = size.GetWidth();
895 const uint16_t height = size.GetWidth();
897 // If either the width or height has been specified, include the resizing options in the hash
898 if( width != 0 || height != 0 )
900 // We are appending 5 bytes to the URL to form the hash input.
901 hashTarget.resize( urlLength + 5u );
902 char* hashTargetPtr = &( hashTarget[ urlLength ] );
904 // Pack the width and height (4 bytes total).
905 *hashTargetPtr++ = size.GetWidth() & 0xff;
906 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
907 *hashTargetPtr++ = size.GetHeight() & 0xff;
908 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
910 // Bit-pack the FittingMode, SamplingMode and atlasing.
911 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
912 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
916 // We are not including sizing information, but we still need an extra byte for atlasing.
917 hashTarget.resize( urlLength + 1u );
918 // Add the atlasing to the hash input.
919 hashTarget[ urlLength ] = useAtlas;
922 if( maskTextureId != INVALID_TEXTURE_ID )
924 auto textureIdIndex = hashTarget.length();
925 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
926 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
928 // Append the texture id to the end of the URL byte by byte:
929 // (to avoid SIGBUS / alignment issues)
930 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
932 *hashTargetPtr++ = maskTextureId & 0xff;
933 maskTextureId >>= 8u;
937 auto premultipliedIndex = hashTarget.length();
938 hashTarget.resize( premultipliedIndex + 1 );
939 switch( preMultiplyOnLoad )
941 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
943 hashTarget[ premultipliedIndex ] = 't';
946 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
948 hashTarget[ premultipliedIndex ] = 'f';
953 return Dali::CalculateHash( hashTarget );
956 int TextureManager::FindCachedTexture(
957 const TextureManager::TextureHash hash,
958 const std::string& url,
959 const ImageDimensions size,
960 const FittingMode::Type fittingMode,
961 const Dali::SamplingMode::Type samplingMode,
963 TextureId maskTextureId,
964 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
966 // Default to an invalid ID, in case we do not find a match.
967 int cacheIndex = INVALID_CACHE_INDEX;
969 // Iterate through our hashes to find a match.
970 const unsigned int count = mTextureInfoContainer.size();
971 for( unsigned int i = 0u; i < count; ++i )
973 if( mTextureInfoContainer[i].hash == hash )
975 // We have a match, now we check all the original parameters in case of a hash collision.
976 TextureInfo& textureInfo( mTextureInfoContainer[i] );
977 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
978 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
980 if( ( url == textureInfo.url.GetUrl() ) &&
981 ( useAtlas == textureInfo.useAtlas ) &&
982 ( maskTextureId == textureInfo.maskTextureId ) &&
983 ( size == textureInfo.desiredSize ) &&
984 ( preMultiplyOnLoad == multiplyOnLoad ) &&
985 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
986 ( fittingMode == textureInfo.fittingMode &&
987 samplingMode == textureInfo.samplingMode ) ) )
989 // The found Texture is a match.
999 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1001 const unsigned int count = mTextureInfoContainer.size();
1002 for( unsigned int i = 0; i < count; ++i )
1004 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1005 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1006 j != textureInfo.observerList.End(); )
1008 if( *j == observer )
1010 j = textureInfo.observerList.Erase( j );
1021 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1022 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1023 AsyncLoadingInfoContainerType())
1027 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1028 const VisualUrl& url,
1029 ImageDimensions desiredSize,
1030 FittingMode::Type fittingMode,
1031 SamplingMode::Type samplingMode,
1032 bool orientationCorrection)
1034 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1035 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1036 mLoadingInfoContainer.back().loadId = id;
1039 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1040 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1044 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1045 Toolkit::AsyncImageLoader loader,
1046 TextureManager& textureManager,
1047 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1049 mTextureManager(textureManager),
1050 mLoadingInfoContainer(std::move(loadingInfoContainer))
1052 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1053 this, &AsyncLoadingHelper::AsyncLoadComplete);
1056 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1057 Devel::PixelBuffer pixelBuffer)
1059 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1062 } // namespace Internal
1064 } // namespace Toolkit