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.

World.cc 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #include "World.h"
  2. #include <algorithm>
  3. #include <tuple>
  4. #include "log.h"
  5. #include "Game.h"
  6. #include "Win.h"
  7. #include "Clock.h"
  8. #include "assets.h"
  9. namespace Swan {
  10. static void chunkLine(int l, WorldPlane &plane, ChunkPos &abspos, const Vec2i &dir) {
  11. for (int i = 0; i < l; ++i) {
  12. plane.slowGetChunk(abspos).keepActive();
  13. abspos += dir;
  14. }
  15. }
  16. std::vector<ModWrapper> World::loadMods(std::vector<std::string> paths) {
  17. std::vector<ModWrapper> mods;
  18. mods.reserve(paths.size());
  19. for (auto &path: paths) {
  20. OS::Dynlib dl(path + "/mod");
  21. auto create = dl.get<Mod *(*)(World &)>("mod_create");
  22. if (create == NULL) {
  23. warn << path << ": No 'mod_create' function!";
  24. continue;
  25. }
  26. std::unique_ptr<Mod> mod(create(*this));
  27. mods.push_back(ModWrapper(std::move(mod), std::move(path), std::move(dl)));
  28. }
  29. return mods;
  30. }
  31. Cygnet::ResourceManager World::buildResources() {
  32. Cygnet::ResourceBuilder builder(game_->renderer_);
  33. auto fillTileImage = [&](unsigned char *data, int r, int g, int b, int a) {
  34. for (size_t i = 0; i < TILE_SIZE * TILE_SIZE; ++i) {
  35. data[i * 4 + 0] = r;
  36. data[i * 4 + 1] = g;
  37. data[i * 4 + 2] = b;
  38. data[i * 4 + 2] = a;
  39. }
  40. };
  41. struct ImageAsset fallbackImage = {
  42. .width = 32,
  43. .frameHeight = 32,
  44. .frameCount = 1,
  45. .data = std::make_unique<unsigned char[]>(TILE_SIZE * TILE_SIZE * 4),
  46. };
  47. fillTileImage(fallbackImage.data.get(),
  48. PLACEHOLDER_RED, PLACEHOLDER_GREEN, PLACEHOLDER_BLUE, 255);
  49. auto airImage = std::make_unique<unsigned char[]>(TILE_SIZE * TILE_SIZE * 4);
  50. fillTileImage(airImage.get(),
  51. PLACEHOLDER_RED, PLACEHOLDER_GREEN, PLACEHOLDER_BLUE, 255);
  52. // Let tile ID 0 be the invalid tile
  53. builder.addTile(INVALID_TILE_ID, fallbackImage.data.get());
  54. tilesMap_[INVALID_TILE_NAME] = INVALID_TILE_ID;
  55. tiles_.push_back(Tile(INVALID_TILE_ID, INVALID_TILE_NAME, {
  56. .name = "", .image = "", // Not used in this case
  57. .isSolid = false,
  58. }));
  59. items_.emplace(INVALID_TILE_NAME, Item(INVALID_TILE_ID, INVALID_TILE_NAME, {
  60. .name = "", .image = "", // Not used in this case
  61. }));
  62. // ...And tile ID 1 be the air tile
  63. builder.addTile(AIR_TILE_ID, std::move(airImage));
  64. tilesMap_[AIR_TILE_NAME] = AIR_TILE_ID;
  65. tiles_.push_back(Tile(AIR_TILE_ID, AIR_TILE_NAME, {
  66. .name = "", .image = "", // Not used in this case
  67. .isSolid = false,
  68. }));
  69. items_.emplace(AIR_TILE_NAME, Item(AIR_TILE_ID, AIR_TILE_NAME, {
  70. .name = "", .image = "", // Not used in this case
  71. }));
  72. // Assets are namespaced on the mod, so if something references, say,
  73. // "core::stone", we need to know which directory the "core" mod is in
  74. std::unordered_map<std::string, std::string> modPaths;
  75. for (auto &mod: mods_) {
  76. modPaths[mod.mod_->name_] = mod.path_;
  77. }
  78. auto loadTileImage = [&](std::string path) -> Result<ImageAsset> {
  79. // Don't force all tiles/items to have an associated image.
  80. // It could be that some tiles/items exist for a purpose which implies
  81. // it should never actually be visible.
  82. if (path == INVALID_TILE_NAME) {
  83. ImageAsset asset{
  84. .width = 32,
  85. .frameHeight = 32,
  86. .frameCount = 1,
  87. .data = std::make_unique<unsigned char[]>(TILE_SIZE * TILE_SIZE * 4),
  88. };
  89. memcpy(asset.data.get(), fallbackImage.data.get(), TILE_SIZE * TILE_SIZE * 4);
  90. return {Ok, std::move(asset)};
  91. }
  92. auto image = loadImageAsset(modPaths, path);
  93. if (!image) {
  94. warn << '\'' << path << "': " << image.err();
  95. return {Err, '\'' + path + "': " + image.err()};
  96. } else if (image->width != TILE_SIZE) {
  97. warn << '\'' << path << "': Width must be " << TILE_SIZE << " pixels";
  98. return {Err, '\'' + path + "': Width must be " + std::to_string(TILE_SIZE) + " pixels"};
  99. } else {
  100. return image;
  101. }
  102. };
  103. // Need to fill in every tile before we do items,
  104. // because all items will end up after all tiles in the tile atlas.
  105. // In the rendering system, there's no real difference between a tile
  106. // and an item.
  107. for (auto &mod: mods_) {
  108. for (auto &tileBuilder: mod.mod_->tiles_) {
  109. auto image = loadTileImage(tileBuilder.image);
  110. std::string tileName = mod.mod_->name_ + "::" + tileBuilder.name;
  111. Tile::ID tileId = tiles_.size();
  112. if (image) {
  113. builder.addTile(tileId, std::move(image->data));
  114. } else {
  115. warn << image.err();
  116. builder.addTile(tileId, fallbackImage.data.get());
  117. }
  118. tilesMap_[tileName] = tileId;
  119. tiles_.push_back(Tile(tileId, tileName, tileBuilder));
  120. // All tiles should have an item.
  121. // Some items will be overwritten later my mod_->items,
  122. // but if not, this is their default item.
  123. items_.emplace(tileName, Item(tileId, tileName, {
  124. .name = "", .image = "", // Not used in this case
  125. }));
  126. }
  127. }
  128. // Put all items after all the tiles
  129. Tile::ID nextItemId = tiles_.size();
  130. // Load all items which aren't just tiles in disguise.
  131. for (auto &mod: mods_) {
  132. for (auto &itemBuilder: mod.mod_->items_) {
  133. auto image = loadTileImage(itemBuilder.image);
  134. std::string itemName = mod.mod_->name_ + "::" + itemBuilder.name;
  135. Tile::ID itemId = nextItemId++;
  136. if (image) {
  137. builder.addTile(itemId, std::move(image->data));
  138. } else {
  139. warn << image.err();
  140. builder.addTile(itemId, fallbackImage.data.get());
  141. }
  142. items_.emplace(itemName, Item(itemId, itemName, itemBuilder));
  143. }
  144. }
  145. // Load sprites
  146. for (auto &mod: mods_) {
  147. for (auto spritePath: mod.mod_->sprites_) {
  148. std::string path = mod.mod_->name_ + "::" + spritePath;
  149. auto image = loadImageAsset(modPaths, path);
  150. if (image) {
  151. builder.addSprite(
  152. path, image->data.get(), image->width,
  153. image->frameHeight * image->frameCount,
  154. image->frameHeight);
  155. } else {
  156. warn << '\'' << path << "': " << image.err();
  157. builder.addSprite(
  158. path, fallbackImage.data.get(), fallbackImage.width,
  159. fallbackImage.frameHeight * fallbackImage.frameCount,
  160. fallbackImage.frameHeight);
  161. }
  162. }
  163. }
  164. // Load world gens and entities
  165. for (auto &mod: mods_) {
  166. for (auto &worldGenFactory: mod.mod_->worldGens_) {
  167. std::string name = mod.mod_->name_ + "::" + worldGenFactory.name;
  168. worldGenFactories_.emplace(name, worldGenFactory);
  169. }
  170. for (auto &entCollFactory: mod.mod_->entities_) {
  171. std::string name = mod.mod_->name_ + "::" + entCollFactory.name;
  172. entCollFactories_.emplace(name, entCollFactory);
  173. }
  174. }
  175. return Cygnet::ResourceManager(std::move(builder));
  176. }
  177. World::World(Game *game, unsigned long randSeed, std::vector<std::string> modPaths):
  178. game_(game), random_(randSeed), mods_(loadMods(std::move(modPaths))),
  179. resources_(buildResources()) {}
  180. void World::ChunkRenderer::tick(WorldPlane &plane, ChunkPos abspos) {
  181. ZoneScopedN("World::ChunkRenderer tick");
  182. int l = 0;
  183. RTClock clock;
  184. for (int i = 0; i < 4; ++i) {
  185. chunkLine(l, plane, abspos, Vec2i(0, -1));
  186. chunkLine(l, plane, abspos, Vec2i(1, 0));
  187. l += 1;
  188. chunkLine(l, plane, abspos, Vec2i(0, 1));
  189. chunkLine(l, plane, abspos, Vec2i(-1, 0));
  190. l += 1;
  191. }
  192. }
  193. void World::setWorldGen(std::string gen) {
  194. defaultWorldGen_ = std::move(gen);
  195. }
  196. void World::spawnPlayer() {
  197. player_ = &((dynamic_cast<BodyTrait *>(
  198. planes_[currentPlane_]->spawnPlayer().get()))->get(BodyTrait::Tag{}));
  199. }
  200. void World::setCurrentPlane(WorldPlane &plane) {
  201. currentPlane_ = plane.id_;
  202. }
  203. WorldPlane &World::addPlane(const std::string &gen) {
  204. WorldPlane::ID id = planes_.size();
  205. auto it = worldGenFactories_.find(gen);
  206. if (it == worldGenFactories_.end()) {
  207. panic << "Tried to add plane with non-existant world gen " << gen << "!";
  208. abort();
  209. }
  210. std::vector<std::unique_ptr<EntityCollection>> colls;
  211. colls.reserve(entCollFactories_.size());
  212. for (auto &fact: entCollFactories_) {
  213. colls.emplace_back(fact.second.create(fact.second.name));
  214. }
  215. WorldGen::Factory &factory = it->second;
  216. std::unique_ptr<WorldGen> g = factory.create(*this);
  217. planes_.push_back(std::make_unique<WorldPlane>(
  218. id, this, std::move(g), std::move(colls)));
  219. return *planes_[id];
  220. }
  221. Item &World::getItem(const std::string &name) {
  222. auto iter = items_.find(name);
  223. if (iter == items_.end()) {
  224. warn << "Tried to get non-existant item " << name << "!";
  225. return *game_->invalidItem_;
  226. }
  227. return iter->second;
  228. }
  229. Tile::ID World::getTileID(const std::string &name) {
  230. auto iter = tilesMap_.find(name);
  231. if (iter == tilesMap_.end()) {
  232. warn << "Tried to get non-existant item " << name << "!";
  233. return INVALID_TILE_ID;
  234. }
  235. return iter->second;
  236. }
  237. Tile &World::getTile(const std::string &name) {
  238. Tile::ID id = getTileID(name);
  239. return getTileByID(id);
  240. }
  241. SDL_Color World::backgroundColor() {
  242. return planes_[currentPlane_]->backgroundColor();
  243. }
  244. void World::draw(Win &win) {
  245. ZoneScopedN("World draw");
  246. win.cam_ = player_->pos - (win.getSize() / 2) + (player_->size / 2);
  247. planes_[currentPlane_]->draw(win);
  248. }
  249. void World::update(float dt) {
  250. ZoneScopedN("World update");
  251. for (auto &plane: planes_)
  252. plane->update(dt);
  253. }
  254. void World::tick(float dt) {
  255. ZoneScopedN("World tick");
  256. for (auto &plane: planes_)
  257. plane->tick(dt);
  258. chunkRenderer_.tick(
  259. *planes_[currentPlane_],
  260. ChunkPos((int)player_->pos.x / CHUNK_WIDTH, (int)player_->pos.y / CHUNK_HEIGHT));
  261. }
  262. }