2 * Copyright (c) 2017 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
90 } // Anonymous namespace
92 TextureManager::MaskingData::MaskingData()
94 mAlphaMaskId( INVALID_TEXTURE_ID ),
95 mContentScaleFactor( 1.0f ),
100 TextureManager::TextureManager()
101 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
102 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
103 mCurrentTextureId( 0 )
107 TextureSet TextureManager::LoadTexture(
108 VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
109 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
110 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
111 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
112 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
113 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
114 TextureManager::ReloadPolicy reloadPolicy )
116 TextureSet textureSet;
118 loadingStatus = false;
119 textureRect = FULL_ATLAS_RECT;
121 if( VisualUrl::TEXTURE == url.GetProtocolType())
123 std::string location = url.GetLocation();
124 if( location.size() > 0u )
126 TextureId id = std::stoi( location );
127 for( auto&& elem : mExternalTextures )
129 if( elem.textureId == id )
131 return elem.textureSet;
136 else if( synchronousLoading )
141 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
142 orientationCorrection );
145 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
151 textureSet = TextureSet::New();
152 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
155 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
157 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
158 data.GetWidth(), data.GetHeight() );
159 texture.Upload( data );
160 textureSet = TextureSet::New();
161 textureSet.SetTexture( 0u, texture );
165 if( atlasingStatus ) // attempt atlasing
167 textureSet = imageAtlasManager->Add( textureRect, data );
169 if( !textureSet ) // big image, no atlasing or atlasing failed
171 atlasingStatus = false;
172 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
173 data.GetWidth(), data.GetHeight() );
174 texture.Upload( data );
175 textureSet = TextureSet::New();
176 textureSet.SetTexture( 0u, texture );
182 loadingStatus = true;
185 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
187 if( !textureSet ) // big image, no atlasing or atlasing failed
189 atlasingStatus = false;
192 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
193 textureObserver, orientationCorrection, reloadPolicy );
197 textureId = RequestLoad( url,
198 maskInfo->mAlphaMaskId,
199 maskInfo->mContentScaleFactor,
201 fittingMode, samplingMode,
202 TextureManager::NO_ATLAS,
203 maskInfo->mCropToMask,
205 orientationCorrection,
209 TextureManager::LoadState loadState = GetTextureState( textureId );
210 loadingStatus = ( loadState == TextureManager::LOADING );
212 if( loadState == TextureManager::UPLOADED )
214 // UploadComplete has already been called - keep the same texture set
215 textureSet = GetTextureSet( textureId );
220 if( ! atlasingStatus && textureSet )
222 Sampler sampler = Sampler::New();
223 sampler.SetWrapMode( wrapModeU, wrapModeV );
224 textureSet.SetSampler( 0u, sampler );
230 TextureManager::TextureId TextureManager::RequestLoad(
231 const VisualUrl& url,
232 const ImageDimensions desiredSize,
233 FittingMode::Type fittingMode,
234 Dali::SamplingMode::Type samplingMode,
235 const UseAtlas useAtlas,
236 TextureUploadObserver* observer,
237 bool orientationCorrection,
238 TextureManager::ReloadPolicy reloadPolicy )
240 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
241 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
244 TextureManager::TextureId TextureManager::RequestLoad(
245 const VisualUrl& url,
246 TextureId maskTextureId,
248 const ImageDimensions desiredSize,
249 FittingMode::Type fittingMode,
250 Dali::SamplingMode::Type samplingMode,
251 const UseAtlas useAtlas,
253 TextureUploadObserver* observer,
254 bool orientationCorrection,
255 TextureManager::ReloadPolicy reloadPolicy )
257 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
258 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
261 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
263 // Use the normal load procedure to get the alpha mask.
264 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
265 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
266 TextureManager::ReloadPolicy::CACHED );
269 TextureManager::TextureId TextureManager::RequestLoadInternal(
270 const VisualUrl& url,
271 TextureId maskTextureId,
273 const ImageDimensions desiredSize,
274 FittingMode::Type fittingMode,
275 Dali::SamplingMode::Type samplingMode,
278 StorageType storageType,
279 TextureUploadObserver* observer,
280 bool orientationCorrection,
281 TextureManager::ReloadPolicy reloadPolicy )
283 // First check if the requested Texture is cached.
284 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
287 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
289 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
290 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
293 // Check if the requested Texture exists in the cache.
294 if( cacheIndex != INVALID_CACHE_INDEX )
296 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
298 // Mark this texture being used by another client resource. Forced reload would replace the current texture
299 // without the need for incrementing the reference count.
300 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
302 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
303 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
304 url.GetUrl().c_str(), observer, cacheIndex, textureId );
307 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
309 // We need a new Texture.
310 textureId = GenerateUniqueTextureId();
311 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
312 desiredSize, contentScale, fittingMode, samplingMode,
313 false, cropToMask, useAtlas, textureHash, orientationCorrection ) );
314 cacheIndex = mTextureInfoContainer.size() - 1u;
316 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
317 url.GetUrl().c_str(), observer, cacheIndex, textureId );
320 // The below code path is common whether we are using the cache or not.
321 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
322 // or a new TextureInfo just created.
323 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
324 textureInfo.maskTextureId = maskTextureId;
325 textureInfo.storageType = storageType;
326 textureInfo.orientationCorrection = orientationCorrection;
328 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
329 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
330 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
331 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
332 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
334 // Force reloading of texture by setting loadState unless already loading or cancelled.
335 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
336 TextureManager::CANCELLED != textureInfo.loadState )
338 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
339 url.GetUrl().c_str(), observer, cacheIndex, textureId );
340 textureInfo.loadState = TextureManager::NOT_STARTED;
343 // Check if we should add the observer.
344 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
345 switch( textureInfo.loadState )
347 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
348 case TextureManager::NOT_STARTED:
350 LoadTexture( textureInfo );
351 ObserveTexture( textureInfo, observer );
354 case TextureManager::LOADING:
356 ObserveTexture( textureInfo, observer );
359 case TextureManager::UPLOADED:
363 // The Texture has already loaded. The other observers have already been notified.
364 // We need to send a "late" loaded notification for this observer.
365 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
366 textureInfo.useAtlas, textureInfo.atlasRect );
370 case TextureManager::CANCELLED:
372 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
373 // (it's ref count has already been incremented, above)
374 textureInfo.loadState = TextureManager::LOADING;
375 ObserveTexture( textureInfo, observer );
378 case TextureManager::LOAD_FINISHED:
379 case TextureManager::WAITING_FOR_MASK:
380 // Loading has already completed. Do nothing.
384 // Return the TextureId for which this Texture can now be referenced by externally.
388 void TextureManager::Remove( const TextureManager::TextureId textureId )
390 int textureInfoIndex = GetCacheIndexFromId( textureId );
391 if( textureInfoIndex != INVALID_INDEX )
393 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
395 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
396 textureId, textureInfoIndex,
397 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
398 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
399 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
400 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
402 // Decrement the reference count and check if this is the last user of this Texture.
403 if( --textureInfo.referenceCount <= 0 )
405 // This is the last remove for this Texture.
406 textureInfo.referenceCount = 0;
407 bool removeTextureInfo = false;
409 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
410 if( textureInfo.loadState == UPLOADED )
412 if( textureInfo.atlas )
414 textureInfo.atlas.Remove( textureInfo.atlasRect );
416 removeTextureInfo = true;
418 else if( textureInfo.loadState == LOADING )
420 // We mark the textureInfo for removal.
421 // Once the load has completed, this method will be called again.
422 textureInfo.loadState = CANCELLED;
426 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
427 removeTextureInfo = true;
430 // If the state allows us to remove the TextureInfo data, we do so.
431 if( removeTextureInfo )
433 // Permanently remove the textureInfo struct.
434 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
440 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
442 int cacheIndex = GetCacheIndexFromId( textureId );
443 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
445 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
446 return cachedTextureInfo.url;
449 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
451 LoadState loadState = TextureManager::NOT_STARTED;
453 int cacheIndex = GetCacheIndexFromId( textureId );
454 if( cacheIndex != INVALID_CACHE_INDEX )
456 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
457 loadState = cachedTextureInfo.loadState;
462 TextureSet TextureManager::GetTextureSet( TextureId textureId )
464 TextureSet textureSet;// empty handle
466 int cacheIndex = GetCacheIndexFromId( textureId );
467 if( cacheIndex != INVALID_CACHE_INDEX )
469 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
470 textureSet = cachedTextureInfo.textureSet;
475 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
477 TextureManager::ExternalTextureInfo info;
478 info.textureId = GenerateUniqueTextureId();
479 info.textureSet = textureSet;
480 mExternalTextures.emplace_back( info );
481 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
484 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
486 if( url.size() > 0u )
488 // get the location from the Url
489 VisualUrl parseUrl( url );
490 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
492 std::string location = parseUrl.GetLocation();
493 if( location.size() > 0u )
495 TextureId id = std::stoi( location );
496 const auto end = mExternalTextures.end();
497 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
499 if( iter->textureId == id )
501 auto textureSet = iter->textureSet;
502 mExternalTextures.erase( iter );
512 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
516 if( textureInfo.loadState == NOT_STARTED )
518 textureInfo.loadState = LOADING;
520 if( !textureInfo.loadSynchronously )
522 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
523 auto loadingHelperIt = loadersContainer.GetNext();
524 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
525 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
526 textureInfo.desiredSize, textureInfo.fittingMode,
527 textureInfo.samplingMode, textureInfo.orientationCorrection );
534 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
535 TextureUploadObserver* observer )
539 textureInfo.observerList.PushBack( observer );
540 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
544 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
545 Devel::PixelBuffer pixelBuffer )
547 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
549 if( loadingContainer.size() >= 1u )
551 AsyncLoadingInfo loadingInfo = loadingContainer.front();
553 if( loadingInfo.loadId == id )
555 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
556 if( cacheIndex != INVALID_CACHE_INDEX )
558 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
560 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
562 if( textureInfo.loadState != CANCELLED )
564 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
565 PostLoad( textureInfo, pixelBuffer );
569 Remove( textureInfo.textureId );
574 loadingContainer.pop_front();
578 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
580 // Was the load successful?
581 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
583 // No atlas support for now
584 textureInfo.useAtlas = NO_ATLAS;
586 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
588 // If there is a mask texture ID associated with this texture, then apply the mask
589 // if it's already loaded. If it hasn't, and the mask is still loading,
590 // wait for the mask to finish loading.
591 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
593 LoadState maskLoadState = GetTextureState( textureInfo.maskTextureId );
594 if( maskLoadState == LOADING )
596 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
597 textureInfo.loadState = WAITING_FOR_MASK;
599 else if( maskLoadState == LOAD_FINISHED )
601 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
602 UploadTexture( pixelBuffer, textureInfo );
603 NotifyObservers( textureInfo, true );
608 UploadTexture( pixelBuffer, textureInfo );
609 NotifyObservers( textureInfo, true );
614 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
615 textureInfo.loadState = LOAD_FINISHED;
617 // Check if there was another texture waiting for this load to complete
618 // (e.g. if this was an image mask, and its load is on a different thread)
619 CheckForWaitingTexture( textureInfo );
624 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
625 // @todo If the load was unsuccessful, upload the broken image.
626 textureInfo.loadState = LOAD_FAILED;
627 CheckForWaitingTexture( textureInfo );
628 NotifyObservers( textureInfo, false );
632 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
634 // Search the cache, checking if any texture has this texture id as a
636 const unsigned int size = mTextureInfoContainer.size();
638 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
640 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
641 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
643 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
644 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
645 textureInfo.pixelBuffer.Reset();
647 if( maskTextureInfo.loadState == LOAD_FINISHED )
649 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
650 UploadTexture( pixelBuffer, textureInfo );
651 NotifyObservers( textureInfo, true );
655 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
656 textureInfo.loadState = LOAD_FAILED;
657 NotifyObservers( textureInfo, false );
663 void TextureManager::ApplyMask(
664 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
665 float contentScale, bool cropToMask )
667 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
668 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
669 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
672 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
674 if( textureInfo.useAtlas != USE_ATLAS )
676 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
678 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
679 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
680 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
681 texture.Upload( pixelData );
682 if ( ! textureInfo.textureSet )
684 textureInfo.textureSet = TextureSet::New();
686 textureInfo.textureSet.SetTexture( 0u, texture );
689 // Update the load state.
690 // Note: This is regardless of success as we care about whether a
691 // load attempt is in progress or not. If unsuccessful, a broken
692 // image is still loaded.
693 textureInfo.loadState = UPLOADED;
696 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
698 TextureId textureId = textureInfo.textureId;
700 // If there is an observer: Notify the load is complete, whether successful or not,
701 // and erase it from the list
702 unsigned int observerCount = textureInfo.observerList.Count();
703 TextureInfo* info = &textureInfo;
705 while( observerCount )
707 TextureUploadObserver* observer = info->observerList[0];
709 // During UploadComplete() a Control ResourceReady() signal is emitted.
710 // During that signal the app may add remove /add Textures (e.g. via
711 // ImageViews). At this point no more observers can be added to the
712 // observerList, because textureInfo.loadState = UPLOADED. However it is
713 // possible for observers to be removed, hence we check the observer list
714 // count every iteration.
716 // The reference to the textureInfo struct can also become invalidated,
717 // because new load requests can modify the mTextureInfoContainer list
718 // (e.g. if more requests are pushed back it can cause the list to be
719 // resized invalidating the reference to the TextureInfo ).
720 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect );
721 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
723 // Get the textureInfo from the container again as it may have been
726 int textureInfoIndex = GetCacheIndexFromId( textureId );
727 if( textureInfoIndex == INVALID_CACHE_INDEX)
729 return; // texture has been removed - can stop.
732 info = &mTextureInfoContainer[ textureInfoIndex ];
733 observerCount = info->observerList.Count();
734 if ( observerCount > 0 )
736 // remove the observer that was just triggered if it's still in the list
737 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
741 info->observerList.Erase( j );
750 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
752 return mCurrentTextureId++;
755 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
757 const unsigned int size = mTextureInfoContainer.size();
759 for( unsigned int i = 0; i < size; ++i )
761 if( mTextureInfoContainer[i].textureId == textureId )
767 DALI_LOG_WARNING( "Cannot locate TextureId: %d\n", textureId );
768 return INVALID_CACHE_INDEX;
771 TextureManager::TextureHash TextureManager::GenerateHash(
772 const std::string& url,
773 const ImageDimensions size,
774 const FittingMode::Type fittingMode,
775 const Dali::SamplingMode::Type samplingMode,
776 const UseAtlas useAtlas,
777 TextureId maskTextureId )
779 std::string hashTarget( url );
780 const size_t urlLength = hashTarget.length();
781 const uint16_t width = size.GetWidth();
782 const uint16_t height = size.GetWidth();
784 // If either the width or height has been specified, include the resizing options in the hash
785 if( width != 0 || height != 0 )
787 // We are appending 5 bytes to the URL to form the hash input.
788 hashTarget.resize( urlLength + 5u );
789 char* hashTargetPtr = &( hashTarget[ urlLength ] );
791 // Pack the width and height (4 bytes total).
792 *hashTargetPtr++ = size.GetWidth() & 0xff;
793 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
794 *hashTargetPtr++ = size.GetHeight() & 0xff;
795 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
797 // Bit-pack the FittingMode, SamplingMode and atlasing.
798 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
799 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
803 // We are not including sizing information, but we still need an extra byte for atlasing.
804 hashTarget.resize( urlLength + 1u );
805 // Add the atlasing to the hash input.
806 hashTarget[ urlLength ] = useAtlas;
809 if( maskTextureId != INVALID_TEXTURE_ID )
811 hashTarget.resize( urlLength + sizeof( TextureId ) );
812 TextureId* hashTargetPtr = reinterpret_cast<TextureId*>(&( hashTarget[ urlLength ] ));
814 // Append the hash target to the end of the URL byte by byte:
815 // (to avoid SIGBUS / alignment issues)
816 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
818 *hashTargetPtr++ = maskTextureId & 0xff;
819 maskTextureId >>= 8u;
823 return Dali::CalculateHash( hashTarget );
826 int TextureManager::FindCachedTexture(
827 const TextureManager::TextureHash hash,
828 const std::string& url,
829 const ImageDimensions size,
830 const FittingMode::Type fittingMode,
831 const Dali::SamplingMode::Type samplingMode,
833 TextureId maskTextureId)
835 // Default to an invalid ID, in case we do not find a match.
836 int cacheIndex = INVALID_CACHE_INDEX;
838 // Iterate through our hashes to find a match.
839 const unsigned int count = mTextureInfoContainer.size();
840 for( unsigned int i = 0u; i < count; ++i )
842 if( mTextureInfoContainer[i].hash == hash )
844 // We have a match, now we check all the original parameters in case of a hash collision.
845 TextureInfo& textureInfo( mTextureInfoContainer[i] );
847 if( ( url == textureInfo.url.GetUrl() ) &&
848 ( useAtlas == textureInfo.useAtlas ) &&
849 ( maskTextureId == textureInfo.maskTextureId ) &&
850 ( size == textureInfo.desiredSize ) &&
851 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
852 ( fittingMode == textureInfo.fittingMode &&
853 samplingMode == textureInfo.samplingMode ) ) )
855 // The found Texture is a match.
865 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
867 const unsigned int count = mTextureInfoContainer.size();
868 for( unsigned int i = 0; i < count; ++i )
870 TextureInfo& textureInfo( mTextureInfoContainer[i] );
871 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
872 j != textureInfo.observerList.End(); )
876 j = textureInfo.observerList.Erase( j );
886 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
887 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
888 AsyncLoadingInfoContainerType())
892 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
893 const VisualUrl& url,
894 ImageDimensions desiredSize,
895 FittingMode::Type fittingMode,
896 SamplingMode::Type samplingMode,
897 bool orientationCorrection)
899 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
900 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
901 mLoadingInfoContainer.back().loadId = id;
904 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
905 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
909 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
910 Toolkit::AsyncImageLoader loader,
911 TextureManager& textureManager,
912 AsyncLoadingInfoContainerType&& loadingInfoContainer)
914 mTextureManager(textureManager),
915 mLoadingInfoContainer(std::move(loadingInfoContainer))
917 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
918 this, &AsyncLoadingHelper::AsyncLoadComplete);
921 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
922 Devel::PixelBuffer pixelBuffer)
924 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
927 } // namespace Internal
929 } // namespace Toolkit