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.

Chunk.h 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma once
  2. #include <SFML/Graphics/Texture.hpp>
  3. #include <string.h>
  4. #include <stdint.h>
  5. #include <memory>
  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. ChunkPos pos_;
  15. Chunk(ChunkPos pos): pos_(pos) {
  16. data_.reset(new uint8_t[CHUNK_WIDTH * CHUNK_HEIGHT * sizeof(Tile::ID)]);
  17. visuals_.reset(new Visuals());
  18. visuals_->tex_.create(CHUNK_WIDTH * TILE_SIZE, CHUNK_HEIGHT * TILE_SIZE);
  19. visuals_->sprite_ = sf::Sprite(visuals_->tex_);
  20. visuals_->dirty_ = false;
  21. }
  22. Tile::ID *getTileData();
  23. Tile::ID getTileID(RelPos pos);
  24. void setTileID(RelPos pos, Tile::ID id);
  25. void drawBlock(RelPos pos, const Tile &t);
  26. void compress();
  27. void decompress();
  28. void render(const Context &ctx);
  29. void draw(const Context &ctx, Win &win);
  30. void tick();
  31. bool keepActive(); // Returns true if chunk was inactive
  32. bool isActive() { return active_timer_ != 0; }
  33. private:
  34. static constexpr int ACTIVE_TIMEOUT = 200;
  35. static sf::Uint8 *renderbuf;
  36. bool isCompressed() { return compressed_size_ != -1; }
  37. std::unique_ptr<uint8_t[]> data_;
  38. ssize_t compressed_size_ = -1; // -1 if not compressed, a positive number if compressed
  39. bool need_render_ = false;
  40. int active_timer_ = ACTIVE_TIMEOUT;
  41. struct Visuals {
  42. sf::Texture tex_;
  43. sf::Sprite sprite_;
  44. bool dirty_;
  45. };
  46. std::unique_ptr<Visuals> visuals_;
  47. };
  48. }