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); } ),
119 mCurrentTextureId( 0 )
123 TextureManager::~TextureManager()
125 for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
127 (*iter)->TextureManagerDestroyed();
131 TextureSet TextureManager::LoadTexture(
132 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
133 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
134 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
135 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
136 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
137 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
138 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
140 TextureSet textureSet;
142 loadingStatus = false;
143 textureRect = FULL_ATLAS_RECT;
145 if( VisualUrl::TEXTURE == url.GetProtocolType())
147 std::string location = url.GetLocation();
148 if( location.size() > 0u )
150 TextureId id = std::stoi( location );
151 for( auto&& elem : mExternalTextures )
153 if( elem.textureId == id )
155 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
156 textureId = elem.textureId;
157 return elem.textureSet;
162 else if( synchronousLoading )
167 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
168 orientationCorrection );
171 PreMultiply( pixelBuffer, preMultiplyOnLoad );
172 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
178 textureSet = TextureSet::New();
179 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
182 PreMultiply( pixelBuffer, preMultiplyOnLoad );
183 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
185 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
186 data.GetWidth(), data.GetHeight() );
187 texture.Upload( data );
188 textureSet = TextureSet::New();
189 textureSet.SetTexture( 0u, texture );
193 if( atlasingStatus ) // attempt atlasing
195 textureSet = imageAtlasManager->Add( textureRect, data );
197 if( !textureSet ) // big image, no atlasing or atlasing failed
199 atlasingStatus = false;
200 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
201 data.GetWidth(), data.GetHeight() );
202 texture.Upload( data );
203 textureSet = TextureSet::New();
204 textureSet.SetTexture( 0u, texture );
210 loadingStatus = true;
213 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
215 if( !textureSet ) // big image, no atlasing or atlasing failed
217 atlasingStatus = false;
220 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
221 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
225 textureId = RequestLoad( url,
226 maskInfo->mAlphaMaskId,
227 maskInfo->mContentScaleFactor,
229 fittingMode, samplingMode,
230 TextureManager::NO_ATLAS,
231 maskInfo->mCropToMask,
233 orientationCorrection,
234 reloadPolicy, preMultiplyOnLoad );
237 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
238 loadingStatus = ( loadState == TextureManager::LOADING );
240 if( loadState == TextureManager::UPLOADED )
242 // UploadComplete has already been called - keep the same texture set
243 textureSet = GetTextureSet( textureId );
248 if( ! atlasingStatus && textureSet )
250 Sampler sampler = Sampler::New();
251 sampler.SetWrapMode( wrapModeU, wrapModeV );
252 textureSet.SetSampler( 0u, sampler );
258 TextureManager::TextureId TextureManager::RequestLoad(
259 const VisualUrl& url,
260 const ImageDimensions desiredSize,
261 FittingMode::Type fittingMode,
262 Dali::SamplingMode::Type samplingMode,
263 const UseAtlas useAtlas,
264 TextureUploadObserver* observer,
265 bool orientationCorrection,
266 TextureManager::ReloadPolicy reloadPolicy,
267 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
269 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
270 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
274 TextureManager::TextureId TextureManager::RequestLoad(
275 const VisualUrl& url,
276 TextureId maskTextureId,
278 const ImageDimensions desiredSize,
279 FittingMode::Type fittingMode,
280 Dali::SamplingMode::Type samplingMode,
281 const UseAtlas useAtlas,
283 TextureUploadObserver* observer,
284 bool orientationCorrection,
285 TextureManager::ReloadPolicy reloadPolicy,
286 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
288 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
289 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
293 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
295 // Use the normal load procedure to get the alpha mask.
296 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
297 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
298 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
299 TextureManager::ReloadPolicy::CACHED, preMultiply );
302 TextureManager::TextureId TextureManager::RequestLoadInternal(
303 const VisualUrl& url,
304 TextureId maskTextureId,
306 const ImageDimensions desiredSize,
307 FittingMode::Type fittingMode,
308 Dali::SamplingMode::Type samplingMode,
311 StorageType storageType,
312 TextureUploadObserver* observer,
313 bool orientationCorrection,
314 TextureManager::ReloadPolicy reloadPolicy,
315 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
317 // First check if the requested Texture is cached.
318 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
319 maskTextureId, preMultiplyOnLoad );
321 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
323 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
324 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
325 maskTextureId, preMultiplyOnLoad );
327 // Check if the requested Texture exists in the cache.
328 if( cacheIndex != INVALID_CACHE_INDEX )
330 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
332 // Mark this texture being used by another client resource. Forced reload would replace the current texture
333 // without the need for incrementing the reference count.
334 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
336 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
337 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
338 url.GetUrl().c_str(), observer, cacheIndex, textureId );
341 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
343 // We need a new Texture.
344 textureId = GenerateUniqueTextureId();
345 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
346 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
347 desiredSize, contentScale, fittingMode, samplingMode,
348 false, cropToMask, useAtlas, textureHash, orientationCorrection,
350 cacheIndex = mTextureInfoContainer.size() - 1u;
352 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
353 url.GetUrl().c_str(), observer, cacheIndex, textureId );
356 // The below code path is common whether we are using the cache or not.
357 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
358 // or a new TextureInfo just created.
359 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
360 textureInfo.maskTextureId = maskTextureId;
361 textureInfo.storageType = storageType;
362 textureInfo.orientationCorrection = orientationCorrection;
364 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
365 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
366 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
367 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
368 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
370 // Force reloading of texture by setting loadState unless already loading or cancelled.
371 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
372 TextureManager::CANCELLED != textureInfo.loadState )
374 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
375 url.GetUrl().c_str(), observer, cacheIndex, textureId );
376 textureInfo.loadState = TextureManager::NOT_STARTED;
379 // Check if we should add the observer.
380 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
381 switch( textureInfo.loadState )
383 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
384 case TextureManager::NOT_STARTED:
386 LoadTexture( textureInfo );
387 ObserveTexture( textureInfo, observer );
390 case TextureManager::LOADING:
392 ObserveTexture( textureInfo, observer );
395 case TextureManager::UPLOADED:
399 // The Texture has already loaded. The other observers have already been notified.
400 // We need to send a "late" loaded notification for this observer.
401 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
402 textureInfo.useAtlas, textureInfo.atlasRect,
403 textureInfo.preMultiplied );
407 case TextureManager::CANCELLED:
409 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
410 // (it's ref count has already been incremented, above)
411 textureInfo.loadState = TextureManager::LOADING;
412 ObserveTexture( textureInfo, observer );
415 case TextureManager::LOAD_FINISHED:
416 case TextureManager::WAITING_FOR_MASK:
417 // Loading has already completed. Do nothing.
421 // Return the TextureId for which this Texture can now be referenced by externally.
425 void TextureManager::Remove( const TextureManager::TextureId textureId )
427 int textureInfoIndex = GetCacheIndexFromId( textureId );
428 if( textureInfoIndex != INVALID_INDEX )
430 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
432 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
433 textureId, textureInfoIndex,
434 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
435 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
436 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
437 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
439 // Decrement the reference count and check if this is the last user of this Texture.
440 if( --textureInfo.referenceCount <= 0 )
442 // This is the last remove for this Texture.
443 textureInfo.referenceCount = 0;
444 bool removeTextureInfo = false;
446 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
447 if( textureInfo.loadState == UPLOADED )
449 if( textureInfo.atlas )
451 textureInfo.atlas.Remove( textureInfo.atlasRect );
453 removeTextureInfo = true;
455 else if( textureInfo.loadState == LOADING )
457 // We mark the textureInfo for removal.
458 // Once the load has completed, this method will be called again.
459 textureInfo.loadState = CANCELLED;
463 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
464 removeTextureInfo = true;
467 // If the state allows us to remove the TextureInfo data, we do so.
468 if( removeTextureInfo )
470 // Permanently remove the textureInfo struct.
471 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
477 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
479 int cacheIndex = GetCacheIndexFromId( textureId );
480 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
482 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
483 return cachedTextureInfo.url;
486 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
488 LoadState loadState = TextureManager::NOT_STARTED;
490 int cacheIndex = GetCacheIndexFromId( textureId );
491 if( cacheIndex != INVALID_CACHE_INDEX )
493 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
494 loadState = cachedTextureInfo.loadState;
498 for( auto&& elem : mExternalTextures )
500 if( elem.textureId == textureId )
502 loadState = LoadState::UPLOADED;
510 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
512 LoadState loadState = TextureManager::NOT_STARTED;
514 int cacheIndex = GetCacheIndexFromId( textureId );
515 if( cacheIndex != INVALID_CACHE_INDEX )
517 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
518 loadState = cachedTextureInfo.loadState;
524 TextureSet TextureManager::GetTextureSet( TextureId textureId )
526 TextureSet textureSet;// empty handle
528 int cacheIndex = GetCacheIndexFromId( textureId );
529 if( cacheIndex != INVALID_CACHE_INDEX )
531 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
532 textureSet = cachedTextureInfo.textureSet;
536 for( auto&& elem : mExternalTextures )
538 if( elem.textureId == textureId )
540 textureSet = elem.textureSet;
548 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
550 TextureManager::ExternalTextureInfo info;
551 info.textureId = GenerateUniqueTextureId();
552 info.textureSet = textureSet;
553 mExternalTextures.emplace_back( info );
554 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
557 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
559 if( url.size() > 0u )
561 // get the location from the Url
562 VisualUrl parseUrl( url );
563 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
565 std::string location = parseUrl.GetLocation();
566 if( location.size() > 0u )
568 TextureId id = std::stoi( location );
569 const auto end = mExternalTextures.end();
570 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
572 if( iter->textureId == id )
574 auto textureSet = iter->textureSet;
575 mExternalTextures.erase( iter );
586 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
588 // make sure an observer doesn't observe the same object twice
589 // otherwise it will get multiple calls to ObjectDestroyed()
590 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
591 mLifecycleObservers.PushBack( &observer );
594 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
596 // Find the observer...
597 auto endIter = mLifecycleObservers.End();
598 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
600 if( (*iter) == &observer)
602 mLifecycleObservers.Erase( iter );
606 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
610 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
614 if( textureInfo.loadState == NOT_STARTED )
616 textureInfo.loadState = LOADING;
618 if( !textureInfo.loadSynchronously )
620 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
621 auto loadingHelperIt = loadersContainer.GetNext();
622 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
623 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
624 textureInfo.desiredSize, textureInfo.fittingMode,
625 textureInfo.samplingMode, textureInfo.orientationCorrection );
632 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
633 TextureUploadObserver* observer )
637 textureInfo.observerList.PushBack( observer );
638 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
642 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
643 Devel::PixelBuffer pixelBuffer )
645 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
647 if( loadingContainer.size() >= 1u )
649 AsyncLoadingInfo loadingInfo = loadingContainer.front();
651 if( loadingInfo.loadId == id )
653 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
654 if( cacheIndex != INVALID_CACHE_INDEX )
656 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
658 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
660 if( textureInfo.loadState != CANCELLED )
662 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
663 PostLoad( textureInfo, pixelBuffer );
667 Remove( textureInfo.textureId );
672 loadingContainer.pop_front();
676 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
678 // Was the load successful?
679 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
681 // No atlas support for now
682 textureInfo.useAtlas = NO_ATLAS;
684 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
686 // If there is a mask texture ID associated with this texture, then apply the mask
687 // if it's already loaded. If it hasn't, and the mask is still loading,
688 // wait for the mask to finish loading.
689 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
691 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
692 if( maskLoadState == LOADING )
694 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
695 textureInfo.loadState = WAITING_FOR_MASK;
697 else if( maskLoadState == LOAD_FINISHED )
699 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
700 UploadTexture( pixelBuffer, textureInfo );
701 NotifyObservers( textureInfo, true );
706 UploadTexture( pixelBuffer, textureInfo );
707 NotifyObservers( textureInfo, true );
712 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
713 textureInfo.loadState = LOAD_FINISHED;
715 // Check if there was another texture waiting for this load to complete
716 // (e.g. if this was an image mask, and its load is on a different thread)
717 CheckForWaitingTexture( textureInfo );
722 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
723 // @todo If the load was unsuccessful, upload the broken image.
724 textureInfo.loadState = LOAD_FAILED;
725 CheckForWaitingTexture( textureInfo );
726 NotifyObservers( textureInfo, false );
730 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
732 // Search the cache, checking if any texture has this texture id as a
734 const unsigned int size = mTextureInfoContainer.size();
736 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
738 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
739 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
741 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
742 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
743 textureInfo.pixelBuffer.Reset();
745 if( maskTextureInfo.loadState == LOAD_FINISHED )
747 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
748 UploadTexture( pixelBuffer, textureInfo );
749 NotifyObservers( textureInfo, true );
753 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
754 textureInfo.loadState = LOAD_FAILED;
755 NotifyObservers( textureInfo, false );
761 void TextureManager::ApplyMask(
762 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
763 float contentScale, bool cropToMask )
765 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
766 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
767 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
771 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
773 if( textureInfo.useAtlas != USE_ATLAS )
775 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
777 // If the texture doesn't have an alpha channel, can't pre-multiply it.
778 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
779 // the status for use in the observer.
780 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
781 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
782 PreMultiply( pixelBuffer, preMultiply );
783 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
785 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
786 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
788 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
789 texture.Upload( pixelData );
790 if ( ! textureInfo.textureSet )
792 textureInfo.textureSet = TextureSet::New();
794 textureInfo.textureSet.SetTexture( 0u, texture );
797 // Update the load state.
798 // Note: This is regardless of success as we care about whether a
799 // load attempt is in progress or not. If unsuccessful, a broken
800 // image is still loaded.
801 textureInfo.loadState = UPLOADED;
804 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
806 TextureId textureId = textureInfo.textureId;
808 // If there is an observer: Notify the load is complete, whether successful or not,
809 // and erase it from the list
810 unsigned int observerCount = textureInfo.observerList.Count();
811 TextureInfo* info = &textureInfo;
813 while( observerCount )
815 TextureUploadObserver* observer = info->observerList[0];
817 // During UploadComplete() a Control ResourceReady() signal is emitted.
818 // During that signal the app may add remove /add Textures (e.g. via
819 // ImageViews). At this point no more observers can be added to the
820 // observerList, because textureInfo.loadState = UPLOADED. However it is
821 // possible for observers to be removed, hence we check the observer list
822 // count every iteration.
824 // The reference to the textureInfo struct can also become invalidated,
825 // because new load requests can modify the mTextureInfoContainer list
826 // (e.g. if more requests are pushed back it can cause the list to be
827 // resized invalidating the reference to the TextureInfo ).
828 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
829 info->preMultiplied );
830 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
832 // Get the textureInfo from the container again as it may have been
835 int textureInfoIndex = GetCacheIndexFromId( textureId );
836 if( textureInfoIndex == INVALID_CACHE_INDEX)
838 return; // texture has been removed - can stop.
841 info = &mTextureInfoContainer[ textureInfoIndex ];
842 observerCount = info->observerList.Count();
843 if ( observerCount > 0 )
845 // remove the observer that was just triggered if it's still in the list
846 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
850 info->observerList.Erase( j );
859 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
861 return mCurrentTextureId++;
864 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
866 const unsigned int size = mTextureInfoContainer.size();
868 for( unsigned int i = 0; i < size; ++i )
870 if( mTextureInfoContainer[i].textureId == textureId )
876 return INVALID_CACHE_INDEX;
879 TextureManager::TextureHash TextureManager::GenerateHash(
880 const std::string& url,
881 const ImageDimensions size,
882 const FittingMode::Type fittingMode,
883 const Dali::SamplingMode::Type samplingMode,
884 const UseAtlas useAtlas,
885 TextureId maskTextureId,
886 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
888 std::string hashTarget( url );
889 const size_t urlLength = hashTarget.length();
890 const uint16_t width = size.GetWidth();
891 const uint16_t height = size.GetWidth();
893 // If either the width or height has been specified, include the resizing options in the hash
894 if( width != 0 || height != 0 )
896 // We are appending 5 bytes to the URL to form the hash input.
897 hashTarget.resize( urlLength + 5u );
898 char* hashTargetPtr = &( hashTarget[ urlLength ] );
900 // Pack the width and height (4 bytes total).
901 *hashTargetPtr++ = size.GetWidth() & 0xff;
902 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
903 *hashTargetPtr++ = size.GetHeight() & 0xff;
904 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
906 // Bit-pack the FittingMode, SamplingMode and atlasing.
907 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
908 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
912 // We are not including sizing information, but we still need an extra byte for atlasing.
913 hashTarget.resize( urlLength + 1u );
914 // Add the atlasing to the hash input.
915 hashTarget[ urlLength ] = useAtlas;
918 if( maskTextureId != INVALID_TEXTURE_ID )
920 auto textureIdIndex = hashTarget.length();
921 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
922 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
924 // Append the texture id to the end of the URL byte by byte:
925 // (to avoid SIGBUS / alignment issues)
926 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
928 *hashTargetPtr++ = maskTextureId & 0xff;
929 maskTextureId >>= 8u;
933 auto premultipliedIndex = hashTarget.length();
934 hashTarget.resize( premultipliedIndex + 1 );
935 switch( preMultiplyOnLoad )
937 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
939 hashTarget[ premultipliedIndex ] = 't';
942 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
944 hashTarget[ premultipliedIndex ] = 'f';
949 return Dali::CalculateHash( hashTarget );
952 int TextureManager::FindCachedTexture(
953 const TextureManager::TextureHash hash,
954 const std::string& url,
955 const ImageDimensions size,
956 const FittingMode::Type fittingMode,
957 const Dali::SamplingMode::Type samplingMode,
959 TextureId maskTextureId,
960 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
962 // Default to an invalid ID, in case we do not find a match.
963 int cacheIndex = INVALID_CACHE_INDEX;
965 // Iterate through our hashes to find a match.
966 const unsigned int count = mTextureInfoContainer.size();
967 for( unsigned int i = 0u; i < count; ++i )
969 if( mTextureInfoContainer[i].hash == hash )
971 // We have a match, now we check all the original parameters in case of a hash collision.
972 TextureInfo& textureInfo( mTextureInfoContainer[i] );
973 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
974 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
976 if( ( url == textureInfo.url.GetUrl() ) &&
977 ( useAtlas == textureInfo.useAtlas ) &&
978 ( maskTextureId == textureInfo.maskTextureId ) &&
979 ( size == textureInfo.desiredSize ) &&
980 ( preMultiplyOnLoad == multiplyOnLoad ) &&
981 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
982 ( fittingMode == textureInfo.fittingMode &&
983 samplingMode == textureInfo.samplingMode ) ) )
985 // The found Texture is a match.
995 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
997 const unsigned int count = mTextureInfoContainer.size();
998 for( unsigned int i = 0; i < count; ++i )
1000 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1001 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1002 j != textureInfo.observerList.End(); )
1004 if( *j == observer )
1006 j = textureInfo.observerList.Erase( j );
1017 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1018 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1019 AsyncLoadingInfoContainerType())
1023 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1024 const VisualUrl& url,
1025 ImageDimensions desiredSize,
1026 FittingMode::Type fittingMode,
1027 SamplingMode::Type samplingMode,
1028 bool orientationCorrection)
1030 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1031 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1032 mLoadingInfoContainer.back().loadId = id;
1035 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1036 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1040 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1041 Toolkit::AsyncImageLoader loader,
1042 TextureManager& textureManager,
1043 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1045 mTextureManager(textureManager),
1046 mLoadingInfoContainer(std::move(loadingInfoContainer))
1048 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1049 this, &AsyncLoadingHelper::AsyncLoadComplete);
1052 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1053 Devel::PixelBuffer pixelBuffer)
1055 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1058 } // namespace Internal
1060 } // namespace Toolkit