A 2D tile-based sandbox game.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Chunk.h 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #include <string.h>
  3. #include <stdint.h>
  4. #include <memory>
  5. #include "util.h"
  6. #include "common.h"
  7. #include "Tile.h"
  8. namespace Swan {
  9. class World;
  10. class Game;
  11. class Chunk {
  12. public:
  13. using RelPos = TilePos;
  14. // What does this chunk want the world gen to do after a tick?
  15. enum class TickAction {
  16. DEACTIVATE,
  17. DELETE,
  18. NOTHING,
  19. };
  20. Chunk(ChunkPos pos): pos_(pos) {
  21. data_.reset(new uint8_t[CHUNK_WIDTH * CHUNK_HEIGHT * sizeof(Tile::ID)]);
  22. }
  23. Tile::ID *getTileData() {
  24. assert(isActive());
  25. return (Tile::ID *)data_.get();
  26. }
  27. Tile::ID getTileID(RelPos pos) {
  28. return getTileData()[pos.y * CHUNK_WIDTH + pos.x];
  29. }
  30. void setTileID(RelPos pos, Tile::ID id, SDL_Texture *tex) {
  31. getTileData()[pos.y * CHUNK_WIDTH + pos.x] = id;
  32. draw_list_.push_back({ pos, tex });
  33. }
  34. void setTileData(RelPos pos, Tile::ID id) {
  35. getTileData()[pos.y * CHUNK_WIDTH + pos.x] = id;
  36. need_render_ = true;
  37. }
  38. void render(const Context &ctx, SDL_Renderer *rnd);
  39. void compress();
  40. void decompress();
  41. void draw(const Context &ctx, Win &win);
  42. TickAction tick(float dt);
  43. bool isActive() { return deactivate_timer_ > 0; }
  44. void keepActive();
  45. void markModified() { is_modified_ = true; }
  46. ChunkPos pos_;
  47. private:
  48. static constexpr float DEACTIVATE_INTERVAL = 20;
  49. void renderList(SDL_Renderer *rnd);
  50. bool isCompressed() { return compressed_size_ != -1; }
  51. std::unique_ptr<uint8_t[]> data_;
  52. std::vector<std::pair<RelPos, SDL_Texture *>> draw_list_;
  53. ssize_t compressed_size_ = -1; // -1 if not compressed, a positive number if compressed
  54. bool need_render_ = false;
  55. float deactivate_timer_ = DEACTIVATE_INTERVAL;
  56. bool is_modified_ = false;
  57. CPtr<SDL_Texture, SDL_DestroyTexture> texture_;
  58. };
  59. }