resource_loader.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #pragma once
  24. #include "types.h"
  25. #include "resource.h"
  26. #include "thread.h"
  27. #include "container_types.h"
  28. #include "mutex.h"
  29. namespace crown
  30. {
  31. class Bundle;
  32. class Allocator;
  33. struct ResourceData
  34. {
  35. ResourceId id;
  36. void* data;
  37. };
  38. /// Loads resources in a background thread.
  39. ///
  40. /// @ingroup Resource
  41. class ResourceLoader
  42. {
  43. public:
  44. /// Reads the resources data from the given @a bundle using
  45. /// @a resource_heap to allocate memory for them.
  46. ResourceLoader(Bundle& bundle, Allocator& resource_heap);
  47. ~ResourceLoader();
  48. /// Loads the @a resource in a background thread.
  49. void load(ResourceId id);
  50. /// Blocks until all pending requests have been processed.
  51. void flush();
  52. void get_loaded(Array<ResourceData>& loaded);
  53. private:
  54. void add_request(ResourceId id);
  55. uint32_t num_requests();
  56. void add_loaded(ResourceData data);
  57. // Loads resources in the loading queue.
  58. int32_t run();
  59. static int32_t thread_proc(void* thiz)
  60. {
  61. ResourceLoader* rl = (ResourceLoader*)thiz;
  62. return rl->run();
  63. }
  64. private:
  65. Thread m_thread;
  66. Bundle& m_bundle;
  67. Allocator& m_resource_heap;
  68. Queue<ResourceId> m_requests;
  69. Queue<ResourceData> m_loaded;
  70. Mutex m_mutex;
  71. Mutex m_loaded_mutex;
  72. bool m_exit;
  73. };
  74. } // namespace crown