BackgroundLoader.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #include "../Container/HashMap.h"
  5. #include "../Container/HashSet.h"
  6. #include "../Core/Mutex.h"
  7. #include "../Container/Ptr.h"
  8. #include "../Container/RefCounted.h"
  9. #include "../Core/Thread.h"
  10. #include "../Math/StringHash.h"
  11. namespace Urho3D
  12. {
  13. class Resource;
  14. class ResourceCache;
  15. /// Queue item for background loading of a resource.
  16. struct BackgroundLoadItem
  17. {
  18. /// Resource.
  19. SharedPtr<Resource> resource_;
  20. /// Resources depended on for loading.
  21. HashSet<Pair<StringHash, StringHash>> dependencies_;
  22. /// Resources that depend on this resource's loading.
  23. HashSet<Pair<StringHash, StringHash>> dependents_;
  24. /// Whether to send failure event.
  25. bool sendEventOnFailure_;
  26. };
  27. /// Background loader of resources. Owned by the ResourceCache.
  28. /// @nobind
  29. class BackgroundLoader : public RefCounted, public Thread
  30. {
  31. public:
  32. /// Construct.
  33. explicit BackgroundLoader(ResourceCache* owner);
  34. /// Destruct. Forcibly clear the load queue.
  35. ~BackgroundLoader() override;
  36. /// Resource background loading loop.
  37. void ThreadFunction() override;
  38. /// Queue loading of a resource. The name must be sanitated to ensure consistent format. Return true if queued (not a duplicate and resource was a known type).
  39. bool QueueResource(StringHash type, const String& name, bool sendEventOnFailure, Resource* caller);
  40. /// Wait and finish possible loading of a resource when being requested from the cache.
  41. void WaitForResource(StringHash type, StringHash nameHash);
  42. /// Process resources that are ready to finish.
  43. void FinishResources(int maxMs);
  44. /// Return amount of resources in the load queue.
  45. unsigned GetNumQueuedResources() const;
  46. private:
  47. /// Finish one background loaded resource.
  48. void FinishBackgroundLoading(BackgroundLoadItem& item);
  49. /// Resource cache.
  50. ResourceCache* owner_;
  51. /// Mutex for thread-safe access to the background load queue.
  52. mutable Mutex backgroundLoadMutex_;
  53. /// Resources that are queued for background loading.
  54. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem> backgroundLoadQueue_;
  55. };
  56. }