A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResourceManager.h 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #include <unordered_map>
  3. #include <optional>
  4. #include <memory>
  5. #include <stdint.h>
  6. #include <string.h>
  7. #include <swan-common/constants.h>
  8. #include "Renderer.h"
  9. #include "TileAtlas.h"
  10. namespace Cygnet {
  11. struct ResourceTileAnimation {
  12. uint16_t id;
  13. int frames;
  14. int index;
  15. std::unique_ptr<unsigned char[]> data;
  16. };
  17. class ResourceManager;
  18. class ResourceBuilder {
  19. public:
  20. ResourceBuilder(Renderer &rnd): rnd_(rnd) {}
  21. RenderSprite addSprite(std::string name, void *data, int width, int height, int frameHeight);
  22. RenderSprite addSprite(std::string name, void *data, int width, int height);
  23. void addTile(Renderer::TileID id, void *data, int frames = 1);
  24. void addTile(Renderer::TileID id, std::unique_ptr<unsigned char[]> data, int frames = 1);
  25. private:
  26. Renderer &rnd_;
  27. std::unordered_map<std::string, RenderSprite> sprites_;
  28. std::vector<ResourceTileAnimation> tileAnims_;
  29. TileAtlas atlas_;
  30. friend ResourceManager;
  31. };
  32. class ResourceManager {
  33. public:
  34. ResourceManager(ResourceBuilder &&builder);
  35. ~ResourceManager();
  36. void tick();
  37. Renderer &rnd_;
  38. std::unordered_map<std::string, RenderSprite> sprites_;
  39. std::unordered_map<std::string, Renderer::TileID> tiles_;
  40. std::vector<ResourceTileAnimation> tileAnims_;
  41. };
  42. inline RenderSprite ResourceBuilder::addSprite(
  43. std::string name, void *data, int width, int height, int fh) {
  44. return sprites_[std::move(name)] = rnd_.createSprite(data, width, height, fh);
  45. }
  46. inline RenderSprite ResourceBuilder::addSprite(
  47. std::string name, void *data, int width, int height) {
  48. return sprites_[std::move(name)] = rnd_.createSprite(data, width, height);
  49. }
  50. inline void ResourceBuilder::addTile(uint16_t id, void *data, int frames) {
  51. if (frames == 0) {
  52. atlas_.addTile(id, data);
  53. } else {
  54. auto ptr = std::make_unique<unsigned char[]>(
  55. SwanCommon::TILE_SIZE * SwanCommon::TILE_SIZE * 4 * frames);
  56. memcpy(ptr.get(), data, SwanCommon::TILE_SIZE * SwanCommon::TILE_SIZE * 4 * frames);
  57. addTile(id, std::move(ptr), frames);
  58. }
  59. }
  60. inline void ResourceBuilder::addTile(Renderer::TileID id, std::unique_ptr<unsigned char[]> data, int frames) {
  61. atlas_.addTile(id, data.get());
  62. if (frames > 1) {
  63. tileAnims_.push_back({
  64. .id = id,
  65. .frames = frames,
  66. .index = 0,
  67. .data = std::move(data),
  68. });
  69. }
  70. }
  71. }