CMapGenerator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #include "StdInc.h"
  2. #include "CMapGenerator.h"
  3. #include "../mapping/CMap.h"
  4. #include "../VCMI_Lib.h"
  5. #include "../CGeneralTextHandler.h"
  6. #include "../mapping/CMapEditManager.h"
  7. #include "../CObjectHandler.h"
  8. #include "../CDefObjInfoHandler.h"
  9. #include "../CTownHandler.h"
  10. #include "../StringConstants.h"
  11. #include "../filesystem/Filesystem.h"
  12. #include "CRmgTemplate.h"
  13. #include "CRmgTemplateZone.h"
  14. #include "CZonePlacer.h"
  15. void CMapGenerator::foreach_neighbour(const int3 &pos, std::function<void(int3& pos)> foo)
  16. {
  17. for(const int3 &dir : dirs)
  18. {
  19. int3 n = pos + dir;
  20. if(map->isInTheMap(n))
  21. foo(pos+dir);
  22. }
  23. }
  24. CMapGenerator::CMapGenerator(shared_ptr<CMapGenOptions> mapGenOptions, int randomSeed /*= std::time(nullptr)*/) :
  25. mapGenOptions(mapGenOptions), randomSeed(randomSeed), monolithIndex(0)
  26. {
  27. rand.setSeed(randomSeed);
  28. }
  29. void CMapGenerator::initTiles()
  30. {
  31. map->initTerrain();
  32. int width = map->width;
  33. int height = map->height;
  34. int level = map->twoLevel ? 2 : 1;
  35. tiles = new CTileInfo**[width];
  36. for (int i = 0; i < width; ++i)
  37. {
  38. tiles[i] = new CTileInfo*[height];
  39. for (int j = 0; j < height; ++j)
  40. {
  41. tiles[i][j] = new CTileInfo[level];
  42. }
  43. }
  44. }
  45. CMapGenerator::~CMapGenerator()
  46. {
  47. //FIXME: what if map is not present anymore?
  48. if (tiles && map)
  49. {
  50. for (int i=0; i < map->width; i++)
  51. {
  52. for(int j=0; j < map->height; j++)
  53. {
  54. delete [] tiles[i][j];
  55. }
  56. delete [] tiles[i];
  57. }
  58. delete [] tiles;
  59. }
  60. }
  61. std::unique_ptr<CMap> CMapGenerator::generate()
  62. {
  63. mapGenOptions->finalize(rand);
  64. map = make_unique<CMap>();
  65. editManager = map->getEditManager();
  66. try
  67. {
  68. editManager->getUndoManager().setUndoRedoLimit(0);
  69. addHeaderInfo();
  70. initTiles();
  71. genZones();
  72. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  73. fillZones();
  74. }
  75. catch (rmgException &e)
  76. {
  77. logGlobal->errorStream() << "Random map generation received exception: " << e.what();
  78. }
  79. return std::move(map);
  80. }
  81. std::string CMapGenerator::getMapDescription() const
  82. {
  83. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  84. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  85. std::stringstream ss;
  86. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  87. ", levels %s, humans %d, computers %d, water %s, monster %s, second expansion map") % mapGenOptions->getMapTemplate()->getName() %
  88. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  89. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  90. monsterStrengthStr[mapGenOptions->getMonsterStrength()]);
  91. for(const auto & pair : mapGenOptions->getPlayersSettings())
  92. {
  93. const auto & pSettings = pair.second;
  94. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  95. {
  96. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  97. }
  98. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  99. {
  100. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  101. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  102. }
  103. }
  104. return ss.str();
  105. }
  106. void CMapGenerator::addPlayerInfo()
  107. {
  108. // Calculate which team numbers exist
  109. std::array<std::list<int>, 2> teamNumbers; // 0= cpu/human, 1= cpu only
  110. int teamOffset = 0;
  111. for(int i = 0; i < 2; ++i)
  112. {
  113. int playerCount = i == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getCompOnlyPlayerCount();
  114. int teamCount = i == 0 ? mapGenOptions->getTeamCount() : mapGenOptions->getCompOnlyTeamCount();
  115. if(playerCount == 0)
  116. {
  117. continue;
  118. }
  119. int playersPerTeam = playerCount /
  120. (teamCount == 0 ? playerCount : teamCount);
  121. int teamCountNorm = teamCount;
  122. if(teamCountNorm == 0)
  123. {
  124. teamCountNorm = playerCount;
  125. }
  126. for(int j = 0; j < teamCountNorm; ++j)
  127. {
  128. for(int k = 0; k < playersPerTeam; ++k)
  129. {
  130. teamNumbers[i].push_back(j + teamOffset);
  131. }
  132. }
  133. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  134. {
  135. teamNumbers[i].push_back(j + teamOffset);
  136. }
  137. teamOffset += teamCountNorm;
  138. }
  139. // Team numbers are assigned randomly to every player
  140. for(const auto & pair : mapGenOptions->getPlayersSettings())
  141. {
  142. const auto & pSettings = pair.second;
  143. PlayerInfo player;
  144. player.canComputerPlay = true;
  145. int j = pSettings.getPlayerType() == EPlayerType::COMP_ONLY ? 1 : 0;
  146. if(j == 0)
  147. {
  148. player.canHumanPlay = true;
  149. }
  150. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  151. player.team = TeamID(*itTeam);
  152. teamNumbers[j].erase(itTeam);
  153. map->players[pSettings.getColor().getNum()] = player;
  154. }
  155. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  156. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  157. }
  158. void CMapGenerator::genZones()
  159. {
  160. editManager->clearTerrain(&rand);
  161. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  162. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  163. auto pcnt = mapGenOptions->getPlayerCount();
  164. auto w = mapGenOptions->getWidth();
  165. auto h = mapGenOptions->getHeight();
  166. auto tmpl = mapGenOptions->getMapTemplate();
  167. zones = tmpl->getZones(); //copy from template (refactor?)
  168. int player_per_side = zones.size() > 4 ? 3 : 2;
  169. int zones_cnt = zones.size() > 4 ? 9 : 4;
  170. logGlobal->infoStream() << boost::format("Map size %d %d, players per side %d") % w % h % player_per_side;
  171. CZonePlacer placer(this);
  172. placer.placeZones(mapGenOptions, &rand);
  173. placer.assignZones(mapGenOptions);
  174. int i = 0;
  175. int part_w = w/player_per_side;
  176. int part_h = h/player_per_side;
  177. for(auto const it : zones)
  178. {
  179. CRmgTemplateZone * zone = it.second;
  180. zone->setType(i < pcnt ? ETemplateZoneType::PLAYER_START : ETemplateZoneType::TREASURE);
  181. this->zones[it.first] = zone;
  182. ++i;
  183. }
  184. logGlobal->infoStream() << "Zones generated successfully";
  185. }
  186. void CMapGenerator::fillZones()
  187. {
  188. logGlobal->infoStream() << "Started filling zones";
  189. createConnections();
  190. for (auto it : zones)
  191. {
  192. //make sure all connections are passable before creating borders
  193. it.second->createBorder(this);
  194. it.second->fill(this);
  195. }
  196. logGlobal->infoStream() << "Zones filled successfully";
  197. }
  198. void CMapGenerator::createConnections()
  199. {
  200. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  201. {
  202. auto zoneA = connection.getZoneA();
  203. auto zoneB = connection.getZoneB();
  204. //rearrange tiles in random order
  205. auto tilesCopy = zoneA->getTileInfo();
  206. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  207. //TODO: hwo to use std::shuffle with our generator?
  208. //std::random_shuffle (tiles.begin(), tiles.end(), &gen->rand.nextInt);
  209. int i, n;
  210. n = (tiles.end() - tiles.begin());
  211. for (i=n-1; i>0; --i)
  212. {
  213. std::swap (tiles.begin()[i],tiles.begin()[rand.nextInt(i+1)]);
  214. }
  215. int3 guardPos(-1,-1,-1);
  216. auto otherZoneTiles = zoneB->getTileInfo();
  217. auto otherZoneCenter = zoneB->getPos();
  218. for (auto tile : tiles)
  219. {
  220. foreach_neighbour (tile, [&guardPos, tile, &otherZoneTiles](int3 &pos)
  221. {
  222. if (vstd::contains(otherZoneTiles, pos))
  223. guardPos = tile;
  224. });
  225. if (guardPos.valid())
  226. {
  227. zoneA->addMonster (this, guardPos, connection.getGuardStrength()); //TODO: set value according to template
  228. //zones can make paths only in their own area
  229. zoneA->crunchPath (this, guardPos, zoneA->getPos(), zoneA->getId()); //make connection towards our zone center
  230. zoneB->crunchPath (this, guardPos, zoneB->getPos(), zoneB->getId()); //make connection towards other zone center
  231. break; //we're done with this connection
  232. }
  233. }
  234. if (!guardPos.valid())
  235. {
  236. auto teleport1 = new CGTeleport;
  237. teleport1->ID = Obj::MONOLITH_TWO_WAY;
  238. teleport1->subID = getNextMonlithIndex();
  239. auto teleport2 = new CGTeleport(*teleport1);
  240. zoneA->addRequiredObject (teleport1, connection.getGuardStrength());
  241. zoneB->addRequiredObject (teleport2, connection.getGuardStrength());
  242. }
  243. }
  244. }
  245. void CMapGenerator::addHeaderInfo()
  246. {
  247. map->version = EMapFormat::SOD;
  248. map->width = mapGenOptions->getWidth();
  249. map->height = mapGenOptions->getHeight();
  250. map->twoLevel = mapGenOptions->getHasTwoLevels();
  251. map->name = VLC->generaltexth->allTexts[740];
  252. map->description = getMapDescription();
  253. map->difficulty = 1;
  254. addPlayerInfo();
  255. }
  256. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  257. {
  258. return zones;
  259. }
  260. bool CMapGenerator::isBlocked(const int3 &tile) const
  261. {
  262. if (!map->isInTheMap(tile))
  263. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  264. return tiles[tile.x][tile.y][tile.z].isBlocked();
  265. }
  266. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  267. {
  268. if (!map->isInTheMap(tile))
  269. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  270. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  271. }
  272. bool CMapGenerator::isPossible(const int3 &tile) const
  273. {
  274. if (!map->isInTheMap(tile))
  275. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  276. return tiles[tile.x][tile.y][tile.z].isPossible();
  277. }
  278. bool CMapGenerator::isFree(const int3 &tile) const
  279. {
  280. if (!map->isInTheMap(tile))
  281. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  282. return tiles[tile.x][tile.y][tile.z].isFree();
  283. }
  284. void CMapGenerator::setOccupied(int3 &tile, ETileType::ETileType state)
  285. {
  286. if (!map->isInTheMap(tile))
  287. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  288. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  289. }
  290. CTileInfo CMapGenerator::getTile(int3 tile) const
  291. {
  292. if (!map->isInTheMap(tile))
  293. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  294. return tiles[tile.x][tile.y][tile.z];
  295. }
  296. void CMapGenerator::setNearestObjectDistance(int3 &tile, int value)
  297. {
  298. if (!map->isInTheMap(tile))
  299. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  300. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  301. }
  302. int CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  303. {
  304. if (!map->isInTheMap(tile))
  305. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  306. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  307. }
  308. int CMapGenerator::getNextMonlithIndex()
  309. {
  310. return monolithIndex++;
  311. }