2 * Copyright (c) 2019 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" );
83 #define GET_LOAD_STATE_STRING( loadState ) \
84 loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" : \
85 loadState == TextureManager::LOADING ? "LOADING" : \
86 loadState == TextureManager::LOAD_FINISHED ? "LOAD_FINISHED" : \
87 loadState == TextureManager::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
88 loadState == TextureManager::MASK_APPLYING ? "MASK_APPLYING" : \
89 loadState == TextureManager::MASK_APPLIED ? "MASK_APPLIED" : \
90 loadState == TextureManager::UPLOADED ? "UPLOADED" : \
91 loadState == TextureManager::CANCELLED ? "CANCELLED" : \
92 loadState == TextureManager::LOAD_FAILED ? "LOAD_FAILED" : "Unknown"
96 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
97 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
98 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
99 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
102 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
104 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
106 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
108 pixelBuffer.MultiplyColorByAlpha();
113 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
117 } // Anonymous namespace
119 TextureManager::MaskingData::MaskingData()
121 mAlphaMaskId( INVALID_TEXTURE_ID ),
122 mContentScaleFactor( 1.0f ),
127 TextureManager::TextureManager()
128 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
129 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
131 mLifecycleObservers(),
134 mCurrentTextureId( 0 ),
135 mQueueLoadFlag(false)
139 TextureManager::~TextureManager()
141 for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
143 (*iter)->TextureManagerDestroyed();
147 TextureSet TextureManager::LoadTexture(
148 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
149 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
150 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
151 Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
152 Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
153 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
154 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
156 TextureSet textureSet;
158 loadingStatus = false;
159 textureRect = FULL_ATLAS_RECT;
161 if( VisualUrl::TEXTURE == url.GetProtocolType())
163 std::string location = url.GetLocation();
164 if( location.size() > 0u )
166 TextureId id = std::stoi( location );
167 for( auto&& elem : mExternalTextures )
169 if( elem.textureId == id )
171 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
172 textureId = elem.textureId;
173 return elem.textureSet;
178 else if( synchronousLoading )
183 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
184 orientationCorrection );
187 PreMultiply( pixelBuffer, preMultiplyOnLoad );
188 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
194 textureSet = TextureSet::New();
195 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
198 PreMultiply( pixelBuffer, preMultiplyOnLoad );
199 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
201 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
202 data.GetWidth(), data.GetHeight() );
203 texture.Upload( data );
204 textureSet = TextureSet::New();
205 textureSet.SetTexture( 0u, texture );
209 if( atlasingStatus ) // attempt atlasing
211 textureSet = imageAtlasManager->Add( textureRect, data );
213 if( !textureSet ) // big image, no atlasing or atlasing failed
215 atlasingStatus = false;
216 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
217 data.GetWidth(), data.GetHeight() );
218 texture.Upload( data );
219 textureSet = TextureSet::New();
220 textureSet.SetTexture( 0u, texture );
224 textureRectSize.SetWidth(data.GetWidth());
225 textureRectSize.SetHeight(data.GetHeight());
231 loadingStatus = true;
234 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
236 if( !textureSet ) // big image, no atlasing or atlasing failed
238 atlasingStatus = false;
241 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
242 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
246 textureId = RequestLoad( url,
247 maskInfo->mAlphaMaskId,
248 maskInfo->mContentScaleFactor,
250 fittingMode, samplingMode,
251 TextureManager::NO_ATLAS,
252 maskInfo->mCropToMask,
254 orientationCorrection,
255 reloadPolicy, preMultiplyOnLoad );
258 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
259 if( loadState == TextureManager::UPLOADED )
261 // UploadComplete has already been called - keep the same texture set
262 textureSet = GetTextureSet( textureId );
265 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
266 // caller that they need to wait.
267 loadingStatus = ( loadState == TextureManager::LOADING ||
268 loadState == TextureManager::WAITING_FOR_MASK ||
269 loadState == TextureManager::MASK_APPLYING ||
270 loadState == TextureManager::MASK_APPLIED ||
271 loadState == TextureManager::NOT_STARTED ||
277 textureRectSize = desiredSize;
281 if( ! atlasingStatus && textureSet )
283 Sampler sampler = Sampler::New();
284 sampler.SetWrapMode( wrapModeU, wrapModeV );
285 textureSet.SetSampler( 0u, sampler );
291 TextureManager::TextureId TextureManager::RequestLoad(
292 const VisualUrl& url,
293 const ImageDimensions desiredSize,
294 FittingMode::Type fittingMode,
295 Dali::SamplingMode::Type samplingMode,
296 const UseAtlas useAtlas,
297 TextureUploadObserver* observer,
298 bool orientationCorrection,
299 TextureManager::ReloadPolicy reloadPolicy,
300 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
302 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
303 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
307 TextureManager::TextureId TextureManager::RequestLoad(
308 const VisualUrl& url,
309 TextureId maskTextureId,
311 const ImageDimensions desiredSize,
312 FittingMode::Type fittingMode,
313 Dali::SamplingMode::Type samplingMode,
314 const UseAtlas useAtlas,
316 TextureUploadObserver* observer,
317 bool orientationCorrection,
318 TextureManager::ReloadPolicy reloadPolicy,
319 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
321 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
322 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
326 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
328 // Use the normal load procedure to get the alpha mask.
329 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
330 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
331 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
332 TextureManager::ReloadPolicy::CACHED, preMultiply );
335 TextureManager::TextureId TextureManager::RequestLoadInternal(
336 const VisualUrl& url,
337 TextureId maskTextureId,
339 const ImageDimensions desiredSize,
340 FittingMode::Type fittingMode,
341 Dali::SamplingMode::Type samplingMode,
344 StorageType storageType,
345 TextureUploadObserver* observer,
346 bool orientationCorrection,
347 TextureManager::ReloadPolicy reloadPolicy,
348 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
350 // First check if the requested Texture is cached.
351 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
354 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
356 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
357 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
358 maskTextureId, preMultiplyOnLoad );
360 // Check if the requested Texture exists in the cache.
361 if( cacheIndex != INVALID_CACHE_INDEX )
363 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
365 // Mark this texture being used by another client resource. Forced reload would replace the current texture
366 // without the need for incrementing the reference count.
367 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
369 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
371 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
372 preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
374 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
375 url.GetUrl().c_str(), observer, cacheIndex, textureId );
378 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
380 // We need a new Texture.
381 textureId = GenerateUniqueTextureId();
382 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
383 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
384 desiredSize, contentScale, fittingMode, samplingMode,
385 false, cropToMask, useAtlas, textureHash, orientationCorrection,
387 cacheIndex = mTextureInfoContainer.size() - 1u;
389 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
390 url.GetUrl().c_str(), observer, cacheIndex, textureId );
393 // The below code path is common whether we are using the cache or not.
394 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
395 // or a new TextureInfo just created.
396 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
397 textureInfo.maskTextureId = maskTextureId;
398 textureInfo.storageType = storageType;
399 textureInfo.orientationCorrection = orientationCorrection;
401 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n",
402 GET_LOAD_STATE_STRING(textureInfo.loadState ) );
404 // Force reloading of texture by setting loadState unless already loading or cancelled.
405 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
406 TextureManager::LOADING != textureInfo.loadState &&
407 TextureManager::WAITING_FOR_MASK != textureInfo.loadState &&
408 TextureManager::MASK_APPLYING != textureInfo.loadState &&
409 TextureManager::MASK_APPLIED != textureInfo.loadState &&
410 TextureManager::CANCELLED != textureInfo.loadState )
412 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
413 url.GetUrl().c_str(), observer, cacheIndex, textureId );
414 textureInfo.loadState = TextureManager::NOT_STARTED;
417 // Check if we should add the observer.
418 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
419 switch( textureInfo.loadState )
421 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
422 case TextureManager::NOT_STARTED:
424 LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
427 case TextureManager::LOADING:
428 case TextureManager::WAITING_FOR_MASK:
429 case TextureManager::MASK_APPLYING:
430 case TextureManager::MASK_APPLIED:
432 ObserveTexture( textureInfo, observer );
435 case TextureManager::UPLOADED:
439 LoadOrQueueTexture( textureInfo, observer );
443 case TextureManager::CANCELLED:
445 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
446 // (it's ref count has already been incremented, above)
447 textureInfo.loadState = TextureManager::LOADING;
448 ObserveTexture( textureInfo, observer );
451 case TextureManager::LOAD_FINISHED:
452 // Loading has already completed. Do nothing.
456 // Return the TextureId for which this Texture can now be referenced by externally.
460 void TextureManager::Remove( const TextureManager::TextureId textureId )
462 int textureInfoIndex = GetCacheIndexFromId( textureId );
463 if( textureInfoIndex != INVALID_INDEX )
465 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
467 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
468 "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s\n",
469 textureId, textureInfo.url.GetUrl().c_str(),
470 textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ) );
472 // Decrement the reference count and check if this is the last user of this Texture.
473 if( --textureInfo.referenceCount <= 0 )
475 // This is the last remove for this Texture.
476 textureInfo.referenceCount = 0;
477 bool removeTextureInfo = false;
479 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
480 if( textureInfo.loadState == UPLOADED )
482 if( textureInfo.atlas )
484 textureInfo.atlas.Remove( textureInfo.atlasRect );
486 removeTextureInfo = true;
488 else if( textureInfo.loadState == LOADING )
490 // We mark the textureInfo for removal.
491 // Once the load has completed, this method will be called again.
492 textureInfo.loadState = CANCELLED;
496 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
497 removeTextureInfo = true;
500 // If the state allows us to remove the TextureInfo data, we do so.
501 if( removeTextureInfo )
503 // Permanently remove the textureInfo struct.
504 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
510 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
512 VisualUrl visualUrl("");
513 int cacheIndex = GetCacheIndexFromId( textureId );
515 if( cacheIndex != INVALID_CACHE_INDEX )
517 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
518 cacheIndex, textureId );
520 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
521 visualUrl = cachedTextureInfo.url;
526 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
528 LoadState loadState = TextureManager::NOT_STARTED;
530 int cacheIndex = GetCacheIndexFromId( textureId );
531 if( cacheIndex != INVALID_CACHE_INDEX )
533 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
534 loadState = cachedTextureInfo.loadState;
538 for( auto&& elem : mExternalTextures )
540 if( elem.textureId == textureId )
542 loadState = LoadState::UPLOADED;
550 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
552 LoadState loadState = TextureManager::NOT_STARTED;
554 int cacheIndex = GetCacheIndexFromId( textureId );
555 if( cacheIndex != INVALID_CACHE_INDEX )
557 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
558 loadState = cachedTextureInfo.loadState;
564 TextureSet TextureManager::GetTextureSet( TextureId textureId )
566 TextureSet textureSet;// empty handle
568 int cacheIndex = GetCacheIndexFromId( textureId );
569 if( cacheIndex != INVALID_CACHE_INDEX )
571 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
572 textureSet = cachedTextureInfo.textureSet;
576 for( auto&& elem : mExternalTextures )
578 if( elem.textureId == textureId )
580 textureSet = elem.textureSet;
588 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
590 TextureManager::ExternalTextureInfo info;
591 info.textureId = GenerateUniqueTextureId();
592 info.textureSet = textureSet;
593 mExternalTextures.emplace_back( info );
594 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
597 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
599 if( url.size() > 0u )
601 // get the location from the Url
602 VisualUrl parseUrl( url );
603 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
605 std::string location = parseUrl.GetLocation();
606 if( location.size() > 0u )
608 TextureId id = std::stoi( location );
609 const auto end = mExternalTextures.end();
610 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
612 if( iter->textureId == id )
614 auto textureSet = iter->textureSet;
615 mExternalTextures.erase( iter );
626 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
628 // make sure an observer doesn't observe the same object twice
629 // otherwise it will get multiple calls to ObjectDestroyed()
630 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
631 mLifecycleObservers.PushBack( &observer );
634 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
636 // Find the observer...
637 auto endIter = mLifecycleObservers.End();
638 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
640 if( (*iter) == &observer)
642 mLifecycleObservers.Erase( iter );
646 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
649 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
651 switch( textureInfo.loadState )
658 QueueLoadTexture( textureInfo, observer );
662 LoadTexture( textureInfo, observer );
670 QueueLoadTexture( textureInfo, observer );
674 // The Texture has already loaded. The other observers have already been notified.
675 // We need to send a "late" loaded notification for this observer.
676 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
677 textureInfo.useAtlas, textureInfo.atlasRect,
678 textureInfo.preMultiplied );
685 case WAITING_FOR_MASK:
694 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
696 auto textureId = textureInfo.textureId;
697 mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
700 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
702 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n",
703 textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
705 textureInfo.loadState = LOADING;
706 if( !textureInfo.loadSynchronously )
708 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
709 auto loadingHelperIt = loadersContainer.GetNext();
710 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
711 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
712 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
713 textureInfo.desiredSize, textureInfo.fittingMode,
714 textureInfo.samplingMode, textureInfo.orientationCorrection,
717 ObserveTexture( textureInfo, observer );
720 void TextureManager::ProcessQueuedTextures()
722 for( auto&& element : mLoadQueue )
724 int cacheIndex = GetCacheIndexFromId( element.mTextureId );
725 if( cacheIndex != INVALID_CACHE_INDEX )
727 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
728 if( textureInfo.loadState == UPLOADED )
730 element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
731 textureInfo.useAtlas, textureInfo.atlasRect,
732 textureInfo.preMultiplied );
736 LoadTexture( textureInfo, element.mObserver );
743 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
744 TextureUploadObserver* observer )
746 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n",
747 textureInfo.url.GetUrl().c_str(), observer );
751 textureInfo.observerList.PushBack( observer );
752 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
756 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
757 Devel::PixelBuffer pixelBuffer )
759 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
761 if( loadingContainer.size() >= 1u )
763 AsyncLoadingInfo loadingInfo = loadingContainer.front();
765 if( loadingInfo.loadId == id )
767 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
768 if( cacheIndex != INVALID_CACHE_INDEX )
770 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
772 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
773 " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n",
774 textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState );
776 if( textureInfo.loadState != CANCELLED )
778 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
779 PostLoad( textureInfo, pixelBuffer );
783 Remove( textureInfo.textureId );
788 loadingContainer.pop_front();
792 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
794 // Was the load successful?
795 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
797 // No atlas support for now
798 textureInfo.useAtlas = NO_ATLAS;
800 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
802 // If there is a mask texture ID associated with this texture, then apply the mask
803 // if it's already loaded. If it hasn't, and the mask is still loading,
804 // wait for the mask to finish loading.
805 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
807 if( textureInfo.loadState == MASK_APPLYING )
809 textureInfo.loadState = MASK_APPLIED;
810 UploadTexture( pixelBuffer, textureInfo );
811 NotifyObservers( textureInfo, true );
815 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
816 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
817 if( maskLoadState == LOADING )
819 textureInfo.loadState = WAITING_FOR_MASK;
821 else if( maskLoadState == LOAD_FINISHED )
823 // Send New Task to Thread
824 ApplyMask( textureInfo, textureInfo.maskTextureId );
830 UploadTexture( pixelBuffer, textureInfo );
831 NotifyObservers( textureInfo, true );
836 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
837 textureInfo.loadState = LOAD_FINISHED;
839 // Check if there was another texture waiting for this load to complete
840 // (e.g. if this was an image mask, and its load is on a different thread)
841 CheckForWaitingTexture( textureInfo );
846 // @todo If the load was unsuccessful, upload the broken image.
847 textureInfo.loadState = LOAD_FAILED;
848 CheckForWaitingTexture( textureInfo );
849 NotifyObservers( textureInfo, false );
853 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
855 // Search the cache, checking if any texture has this texture id as a
857 const unsigned int size = mTextureInfoContainer.size();
859 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
861 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
862 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
864 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
866 if( maskTextureInfo.loadState == LOAD_FINISHED )
868 // Send New Task to Thread
869 ApplyMask( textureInfo, maskTextureInfo.textureId );
873 textureInfo.pixelBuffer.Reset();
874 textureInfo.loadState = LOAD_FAILED;
875 NotifyObservers( textureInfo, false );
881 void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId )
883 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
884 if( maskCacheIndex != INVALID_CACHE_INDEX )
886 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
887 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
888 textureInfo.pixelBuffer.Reset();
890 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n",
891 textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
893 textureInfo.loadState = MASK_APPLYING;
894 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
895 auto loadingHelperIt = loadersContainer.GetNext();
896 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
897 loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask );
901 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
903 if( textureInfo.useAtlas != USE_ATLAS )
905 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
907 // Check if this pixelBuffer is premultiplied
908 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
910 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
911 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
913 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
914 texture.Upload( pixelData );
915 if ( ! textureInfo.textureSet )
917 textureInfo.textureSet = TextureSet::New();
919 textureInfo.textureSet.SetTexture( 0u, texture );
922 // Update the load state.
923 // Note: This is regardless of success as we care about whether a
924 // load attempt is in progress or not. If unsuccessful, a broken
925 // image is still loaded.
926 textureInfo.loadState = UPLOADED;
929 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
931 TextureId textureId = textureInfo.textureId;
933 // If there is an observer: Notify the load is complete, whether successful or not,
934 // and erase it from the list
935 TextureInfo* info = &textureInfo;
937 mQueueLoadFlag = true;
939 while( info->observerList.Count() )
941 TextureUploadObserver* observer = info->observerList[0];
943 // During UploadComplete() a Control ResourceReady() signal is emitted.
944 // During that signal the app may add remove /add Textures (e.g. via
946 // It is possible for observers to be removed from the observer list,
947 // and it is also possible for the mTextureInfoContainer to be modified,
948 // invalidating the reference to the textureInfo struct.
949 // Texture load requests for the same URL are deferred until the end of this
951 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n",
952 textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) );
954 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
955 info->preMultiplied );
956 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
958 // Get the textureInfo from the container again as it may have been invalidated.
959 int textureInfoIndex = GetCacheIndexFromId( textureId );
960 if( textureInfoIndex == INVALID_CACHE_INDEX)
962 break; // texture has been removed - can stop.
964 info = &mTextureInfoContainer[ textureInfoIndex ];
966 // remove the observer that was just triggered if it's still in the list
967 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
971 info->observerList.Erase( j );
977 mQueueLoadFlag = false;
978 ProcessQueuedTextures();
981 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
983 return mCurrentTextureId++;
986 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
988 const unsigned int size = mTextureInfoContainer.size();
990 for( unsigned int i = 0; i < size; ++i )
992 if( mTextureInfoContainer[i].textureId == textureId )
998 return INVALID_CACHE_INDEX;
1001 TextureManager::TextureHash TextureManager::GenerateHash(
1002 const std::string& url,
1003 const ImageDimensions size,
1004 const FittingMode::Type fittingMode,
1005 const Dali::SamplingMode::Type samplingMode,
1006 const UseAtlas useAtlas,
1007 TextureId maskTextureId )
1009 std::string hashTarget( url );
1010 const size_t urlLength = hashTarget.length();
1011 const uint16_t width = size.GetWidth();
1012 const uint16_t height = size.GetWidth();
1014 // If either the width or height has been specified, include the resizing options in the hash
1015 if( width != 0 || height != 0 )
1017 // We are appending 5 bytes to the URL to form the hash input.
1018 hashTarget.resize( urlLength + 5u );
1019 char* hashTargetPtr = &( hashTarget[ urlLength ] );
1021 // Pack the width and height (4 bytes total).
1022 *hashTargetPtr++ = size.GetWidth() & 0xff;
1023 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
1024 *hashTargetPtr++ = size.GetHeight() & 0xff;
1025 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
1027 // Bit-pack the FittingMode, SamplingMode and atlasing.
1028 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1029 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
1033 // We are not including sizing information, but we still need an extra byte for atlasing.
1034 hashTarget.resize( urlLength + 1u );
1036 // Add the atlasing to the hash input.
1039 case UseAtlas::NO_ATLAS:
1041 hashTarget[ urlLength ] = 'f';
1044 case UseAtlas::USE_ATLAS:
1046 hashTarget[ urlLength ] = 't';
1052 if( maskTextureId != INVALID_TEXTURE_ID )
1054 auto textureIdIndex = hashTarget.length();
1055 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
1056 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
1058 // Append the texture id to the end of the URL byte by byte:
1059 // (to avoid SIGBUS / alignment issues)
1060 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
1062 *hashTargetPtr++ = maskTextureId & 0xff;
1063 maskTextureId >>= 8u;
1067 return Dali::CalculateHash( hashTarget );
1070 int TextureManager::FindCachedTexture(
1071 const TextureManager::TextureHash hash,
1072 const std::string& url,
1073 const ImageDimensions size,
1074 const FittingMode::Type fittingMode,
1075 const Dali::SamplingMode::Type samplingMode,
1076 const bool useAtlas,
1077 TextureId maskTextureId,
1078 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
1080 // Default to an invalid ID, in case we do not find a match.
1081 int cacheIndex = INVALID_CACHE_INDEX;
1083 // Iterate through our hashes to find a match.
1084 const unsigned int count = mTextureInfoContainer.size();
1085 for( unsigned int i = 0u; i < count; ++i )
1087 if( mTextureInfoContainer[i].hash == hash )
1089 // We have a match, now we check all the original parameters in case of a hash collision.
1090 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1092 if( ( url == textureInfo.url.GetUrl() ) &&
1093 ( useAtlas == textureInfo.useAtlas ) &&
1094 ( maskTextureId == textureInfo.maskTextureId ) &&
1095 ( size == textureInfo.desiredSize ) &&
1096 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1097 ( fittingMode == textureInfo.fittingMode &&
1098 samplingMode == textureInfo.samplingMode ) ) )
1100 // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1101 // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1102 if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad )
1103 || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) )
1105 // The found Texture is a match.
1116 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1118 const unsigned int count = mTextureInfoContainer.size();
1119 for( unsigned int i = 0; i < count; ++i )
1121 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1122 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1123 j != textureInfo.observerList.End(); )
1125 if( *j == observer )
1127 j = textureInfo.observerList.Erase( j );
1138 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1139 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1140 AsyncLoadingInfoContainerType())
1144 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1145 const VisualUrl& url,
1146 ImageDimensions desiredSize,
1147 FittingMode::Type fittingMode,
1148 SamplingMode::Type samplingMode,
1149 bool orientationCorrection,
1150 DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1152 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1153 auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad );
1154 mLoadingInfoContainer.back().loadId = id;
1157 void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId textureId,
1158 Devel::PixelBuffer pixelBuffer,
1159 Devel::PixelBuffer maskPixelBuffer,
1163 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1164 auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask );
1165 mLoadingInfoContainer.back().loadId = id;
1168 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1169 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1173 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1174 Toolkit::AsyncImageLoader loader,
1175 TextureManager& textureManager,
1176 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1178 mTextureManager(textureManager),
1179 mLoadingInfoContainer(std::move(loadingInfoContainer))
1181 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1182 this, &AsyncLoadingHelper::AsyncLoadComplete);
1185 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1186 Devel::PixelBuffer pixelBuffer )
1188 mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer );
1191 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1193 mBrokenImageUrl = brokenImageUrl;
1196 } // namespace Internal
1198 } // namespace Toolkit