CMapGenerator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 "../mapObjects/CObjectHandler.h"
  8. //#include "../mapObjects/CObjectClassesHandler.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(n);
  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. logGlobal->infoStream() << boost::format("Map size %d %d, players per side %d") % w % h % player_per_side;
  170. CZonePlacer placer(this);
  171. placer.placeZones(mapGenOptions, &rand);
  172. placer.assignZones(mapGenOptions);
  173. int i = 0;
  174. for(auto const it : zones)
  175. {
  176. CRmgTemplateZone * zone = it.second;
  177. zone->setType(i < pcnt ? ETemplateZoneType::PLAYER_START : ETemplateZoneType::TREASURE);
  178. this->zones[it.first] = zone;
  179. ++i;
  180. }
  181. logGlobal->infoStream() << "Zones generated successfully";
  182. }
  183. void CMapGenerator::fillZones()
  184. {
  185. logGlobal->infoStream() << "Started filling zones";
  186. createConnections();
  187. for (auto it : zones)
  188. {
  189. //make sure all connections are passable before creating borders
  190. it.second->createBorder(this);
  191. it.second->fill(this);
  192. }
  193. logGlobal->infoStream() << "Zones filled successfully";
  194. }
  195. void CMapGenerator::createConnections()
  196. {
  197. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  198. {
  199. auto zoneA = connection.getZoneA();
  200. auto zoneB = connection.getZoneB();
  201. //rearrange tiles in random order
  202. auto tilesCopy = zoneA->getTileInfo();
  203. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  204. //TODO: hwo to use std::shuffle with our generator?
  205. //std::random_shuffle (tiles.begin(), tiles.end(), &gen->rand.nextInt);
  206. int i, n;
  207. n = (tiles.end() - tiles.begin());
  208. for (i=n-1; i>0; --i)
  209. {
  210. std::swap (tiles.begin()[i],tiles.begin()[rand.nextInt(i+1)]);
  211. }
  212. int3 guardPos(-1,-1,-1);
  213. auto otherZoneTiles = zoneB->getTileInfo();
  214. auto otherZoneCenter = zoneB->getPos();
  215. for (auto tile : tiles)
  216. {
  217. foreach_neighbour (tile, [&guardPos, tile, &otherZoneTiles](int3 &pos)
  218. {
  219. if (vstd::contains(otherZoneTiles, pos))
  220. guardPos = tile;
  221. });
  222. if (guardPos.valid())
  223. {
  224. zoneA->addMonster (this, guardPos, connection.getGuardStrength()); //TODO: set value according to template
  225. //zones can make paths only in their own area
  226. zoneA->crunchPath (this, guardPos, zoneA->getPos(), zoneA->getId()); //make connection towards our zone center
  227. zoneB->crunchPath (this, guardPos, zoneB->getPos(), zoneB->getId()); //make connection towards other zone center
  228. break; //we're done with this connection
  229. }
  230. }
  231. if (!guardPos.valid())
  232. {
  233. auto teleport1 = new CGTeleport;
  234. teleport1->ID = Obj::MONOLITH_TWO_WAY;
  235. teleport1->subID = getNextMonlithIndex();
  236. auto teleport2 = new CGTeleport(*teleport1);
  237. zoneA->addRequiredObject (teleport1, connection.getGuardStrength());
  238. zoneB->addRequiredObject (teleport2, connection.getGuardStrength());
  239. }
  240. }
  241. }
  242. void CMapGenerator::addHeaderInfo()
  243. {
  244. map->version = EMapFormat::SOD;
  245. map->width = mapGenOptions->getWidth();
  246. map->height = mapGenOptions->getHeight();
  247. map->twoLevel = mapGenOptions->getHasTwoLevels();
  248. map->name = VLC->generaltexth->allTexts[740];
  249. map->description = getMapDescription();
  250. map->difficulty = 1;
  251. addPlayerInfo();
  252. }
  253. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  254. {
  255. return zones;
  256. }
  257. bool CMapGenerator::isBlocked(const int3 &tile) const
  258. {
  259. if (!map->isInTheMap(tile))
  260. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  261. return tiles[tile.x][tile.y][tile.z].isBlocked();
  262. }
  263. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  264. {
  265. if (!map->isInTheMap(tile))
  266. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  267. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  268. }
  269. bool CMapGenerator::isPossible(const int3 &tile) const
  270. {
  271. if (!map->isInTheMap(tile))
  272. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  273. return tiles[tile.x][tile.y][tile.z].isPossible();
  274. }
  275. bool CMapGenerator::isFree(const int3 &tile) const
  276. {
  277. if (!map->isInTheMap(tile))
  278. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  279. return tiles[tile.x][tile.y][tile.z].isFree();
  280. }
  281. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  282. {
  283. if (!map->isInTheMap(tile))
  284. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  285. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  286. }
  287. CTileInfo CMapGenerator::getTile(const int3& tile) const
  288. {
  289. if (!map->isInTheMap(tile))
  290. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  291. return tiles[tile.x][tile.y][tile.z];
  292. }
  293. void CMapGenerator::setNearestObjectDistance(int3 &tile, int value)
  294. {
  295. if (!map->isInTheMap(tile))
  296. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  297. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  298. }
  299. int CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  300. {
  301. if (!map->isInTheMap(tile))
  302. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  303. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  304. }
  305. int CMapGenerator::getNextMonlithIndex()
  306. {
  307. return monolithIndex++;
  308. }