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.

Resource.h 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #pragma once
  2. #include <SDL.h>
  3. #include <stdint.h>
  4. #include <string>
  5. #include <memory>
  6. #include <unordered_map>
  7. #include "common.h"
  8. namespace Swan {
  9. class ImageResource {
  10. public:
  11. ImageResource(
  12. SDL_Renderer *renderer, const std::string &modpath, const std::string &id);
  13. ImageResource(
  14. SDL_Renderer *renderer, const std::string &name,
  15. int w, int h, uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255);
  16. void tick(float dt);
  17. SDL_Rect frameRect(int frame = -1) const {
  18. if (frame == -1) frame = frame_;
  19. return SDL_Rect{ 0, frameHeight_ * frame, surface_->w, frameHeight_ };
  20. }
  21. std::unique_ptr<SDL_Surface, void (*)(SDL_Surface *)> surface_{nullptr, &SDL_FreeSurface};
  22. std::unique_ptr<SDL_Texture, void (*)(SDL_Texture *)> texture_{nullptr, &SDL_DestroyTexture};
  23. int frameHeight_;
  24. int numFrames_;
  25. std::string name_;
  26. int frame_ = 0;
  27. private:
  28. float switchInterval_ = 1;
  29. float switchTimer_ = switchInterval_;
  30. };
  31. class ResourceManager {
  32. public:
  33. ResourceManager(Win &win);
  34. void tick(float dt);
  35. ImageResource &getImage(const std::string &name) const;
  36. void addImage(std::unique_ptr<ImageResource> img) { images_[img->name_] = std::move(img); }
  37. private:
  38. std::unordered_map<std::string, std::unique_ptr<ImageResource>> images_;
  39. };
  40. }