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.

DefaultWorldGen.cc 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "DefaultWorldGen.h"
  2. #include <algorithm>
  3. #include "entities/PlayerEntity.h"
  4. static int grassLevel(const siv::PerlinNoise &perlin, int x) {
  5. return (int)(perlin.noise(x / 50.0, 0) * 13);
  6. }
  7. static int stoneLevel(const siv::PerlinNoise &perlin, int x) {
  8. return (int)(perlin.noise(x / 50.0, 10) * 10) + 10;
  9. }
  10. void DefaultWorldGen::drawBackground(const Swan::Context &ctx, Swan::Win &win, Swan::Vec2 pos) {
  11. int texmin = 10;
  12. int texmax = 20;
  13. if (pos.y > texmin) {
  14. SDL_Texture *tex = bgCave_.texture_.get();
  15. Uint8 alpha = std::clamp(
  16. (pos.y - texmin) / (texmax - texmin), 0.0f, 1.0f) * 255;
  17. Swan::TexAlphaMod amod(tex, alpha);
  18. Swan::Draw::parallaxBackground(
  19. win, tex, std::nullopt, std::nullopt,
  20. pos.x * Swan::TILE_SIZE, pos.y * Swan::TILE_SIZE, 0.7);
  21. }
  22. }
  23. SDL_Color DefaultWorldGen::backgroundColor(Swan::Vec2 pos) {
  24. float y = pos.y;
  25. return Swan::Draw::linearGradient(y, {
  26. { 0, { 128, 220, 250, 255 } },
  27. { 70, { 107, 87, 5, 255 } },
  28. { 100, { 107, 87, 5, 255 } },
  29. { 200, { 20, 20, 23, 255 } },
  30. { 300, { 20, 20, 23, 255 } },
  31. { 500, { 25, 10, 10, 255 } },
  32. { 1000, { 65, 10, 10, 255 } } });
  33. }
  34. Swan::Tile::ID DefaultWorldGen::genTile(Swan::TilePos pos) {
  35. int grass_level = grassLevel(perlin_, pos.x);
  36. int stone_level = stoneLevel(perlin_, pos.x);
  37. // Caves
  38. if (pos.y > grass_level + 7 && perlin_.noise(pos.x / 43.37, pos.y / 16.37) > 0.2)
  39. return tAir_;
  40. if (pos.y > stone_level)
  41. return tStone_;
  42. else if (pos.y > grass_level)
  43. return tDirt_;
  44. else if (pos.y == grass_level)
  45. return tGrass_;
  46. else
  47. return tAir_;
  48. }
  49. void DefaultWorldGen::genChunk(Swan::WorldPlane &plane, Swan::Chunk &chunk) {
  50. for (int cx = 0; cx < Swan::CHUNK_WIDTH; ++cx) {
  51. int tilex = chunk.pos_.x * Swan::CHUNK_WIDTH + cx;
  52. for (int cy = 0; cy < Swan::CHUNK_HEIGHT; ++cy) {
  53. int tiley = chunk.pos_.y * Swan::CHUNK_HEIGHT + cy;
  54. Swan::TilePos pos(tilex, tiley);
  55. Swan::Chunk::RelPos rel(cx, cy);
  56. chunk.setTileData(rel, genTile(pos));
  57. }
  58. }
  59. }
  60. Swan::EntityRef DefaultWorldGen::spawnPlayer(const Swan::Context &ctx) {
  61. int x = 0;
  62. return ctx.plane.spawnEntity<PlayerEntity>(
  63. ctx, Swan::Vec2{ (float)x, (float)grassLevel(perlin_, x) - 4 });
  64. }