CMapGenerator.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 "../CTownHandler.h"
  8. #include "../StringConstants.h"
  9. #include "../filesystem/Filesystem.h"
  10. #include "CRmgTemplate.h"
  11. #include "CRmgTemplateZone.h"
  12. #include "CZonePlacer.h"
  13. #include "../mapObjects/CObjectClassesHandler.h"
  14. void CMapGenerator::foreach_neighbour(const int3 &pos, std::function<void(int3& pos)> foo)
  15. {
  16. for(const int3 &dir : dirs)
  17. {
  18. int3 n = pos + dir;
  19. if(map->isInTheMap(n))
  20. foo(n);
  21. }
  22. }
  23. CMapGenerator::CMapGenerator(shared_ptr<CMapGenOptions> mapGenOptions, int RandomSeed /*= std::time(nullptr)*/) :
  24. mapGenOptions(mapGenOptions), randomSeed(RandomSeed), monolithIndex(0), zonesTotal(0)
  25. {
  26. rand.setSeed(randomSeed);
  27. }
  28. void CMapGenerator::initTiles()
  29. {
  30. map->initTerrain();
  31. int width = map->width;
  32. int height = map->height;
  33. int level = map->twoLevel ? 2 : 1;
  34. tiles = new CTileInfo**[width];
  35. for (int i = 0; i < width; ++i)
  36. {
  37. tiles[i] = new CTileInfo*[height];
  38. for (int j = 0; j < height; ++j)
  39. {
  40. tiles[i][j] = new CTileInfo[level];
  41. }
  42. }
  43. }
  44. CMapGenerator::~CMapGenerator()
  45. {
  46. if (tiles)
  47. {
  48. int width = mapGenOptions->getWidth();
  49. int height = mapGenOptions->getHeight();
  50. for (int i=0; i < width; i++)
  51. {
  52. for(int j=0; j < 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. //updated fuarded tiles will be calculated in CGameState::initMapObjects()
  75. }
  76. catch (rmgException &e)
  77. {
  78. logGlobal->errorStream() << "Random map generation received exception: " << e.what();
  79. }
  80. return std::move(map);
  81. }
  82. std::string CMapGenerator::getMapDescription() const
  83. {
  84. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  85. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  86. std::stringstream ss;
  87. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  88. ", levels %s, humans %d, computers %d, water %s, monster %s, second expansion map") % mapGenOptions->getMapTemplate()->getName() %
  89. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  90. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  91. monsterStrengthStr[mapGenOptions->getMonsterStrength()]);
  92. for(const auto & pair : mapGenOptions->getPlayersSettings())
  93. {
  94. const auto & pSettings = pair.second;
  95. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  96. {
  97. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  98. }
  99. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  100. {
  101. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  102. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  103. }
  104. }
  105. return ss.str();
  106. }
  107. void CMapGenerator::addPlayerInfo()
  108. {
  109. // Calculate which team numbers exist
  110. std::array<std::list<int>, 2> teamNumbers; // 0= cpu/human, 1= cpu only
  111. int teamOffset = 0;
  112. for(int i = 0; i < 2; ++i)
  113. {
  114. int playerCount = i == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getCompOnlyPlayerCount();
  115. int teamCount = i == 0 ? mapGenOptions->getTeamCount() : mapGenOptions->getCompOnlyTeamCount();
  116. if(playerCount == 0)
  117. {
  118. continue;
  119. }
  120. int playersPerTeam = playerCount /
  121. (teamCount == 0 ? playerCount : teamCount);
  122. int teamCountNorm = teamCount;
  123. if(teamCountNorm == 0)
  124. {
  125. teamCountNorm = playerCount;
  126. }
  127. for(int j = 0; j < teamCountNorm; ++j)
  128. {
  129. for(int k = 0; k < playersPerTeam; ++k)
  130. {
  131. teamNumbers[i].push_back(j + teamOffset);
  132. }
  133. }
  134. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  135. {
  136. teamNumbers[i].push_back(j + teamOffset);
  137. }
  138. teamOffset += teamCountNorm;
  139. }
  140. // Team numbers are assigned randomly to every player
  141. for(const auto & pair : mapGenOptions->getPlayersSettings())
  142. {
  143. const auto & pSettings = pair.second;
  144. PlayerInfo player;
  145. player.canComputerPlay = true;
  146. int j = pSettings.getPlayerType() == EPlayerType::COMP_ONLY ? 1 : 0;
  147. if(j == 0)
  148. {
  149. player.canHumanPlay = true;
  150. }
  151. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  152. player.team = TeamID(*itTeam);
  153. teamNumbers[j].erase(itTeam);
  154. map->players[pSettings.getColor().getNum()] = player;
  155. }
  156. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  157. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  158. }
  159. void CMapGenerator::genZones()
  160. {
  161. editManager->clearTerrain(&rand);
  162. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  163. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  164. auto pcnt = mapGenOptions->getPlayerCount();
  165. auto w = mapGenOptions->getWidth();
  166. auto h = mapGenOptions->getHeight();
  167. auto tmpl = mapGenOptions->getMapTemplate();
  168. zones = tmpl->getZones(); //copy from template (refactor?)
  169. int player_per_side = zones.size() > 4 ? 3 : 2;
  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. for(auto const it : zones)
  176. {
  177. CRmgTemplateZone * zone = it.second;
  178. zone->setType(i < pcnt ? ETemplateZoneType::PLAYER_START : ETemplateZoneType::TREASURE);
  179. this->zones[it.first] = zone;
  180. ++i;
  181. }
  182. logGlobal->infoStream() << "Zones generated successfully";
  183. }
  184. void CMapGenerator::fillZones()
  185. {
  186. //init native town count with 0
  187. for (auto faction : VLC->townh->getAllowedFactions())
  188. zonesPerFaction[faction] = 0;
  189. logGlobal->infoStream() << "Started filling zones";
  190. createConnections();
  191. //make sure all connections are passable before creating borders
  192. for (auto it : zones)
  193. {
  194. it.second->createBorder(this);
  195. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  196. it.second->initTownType(this);
  197. }
  198. for (auto it : zones)
  199. {
  200. it.second->fill(this);
  201. }
  202. logGlobal->infoStream() << "Zones filled successfully";
  203. }
  204. void CMapGenerator::createConnections()
  205. {
  206. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  207. {
  208. auto zoneA = connection.getZoneA();
  209. auto zoneB = connection.getZoneB();
  210. //rearrange tiles in random order
  211. auto tilesCopy = zoneA->getTileInfo();
  212. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  213. RandomGeneratorUtil::randomShuffle(tiles, rand);
  214. int3 guardPos(-1,-1,-1);
  215. auto otherZoneTiles = zoneB->getTileInfo();
  216. int3 posA = zoneA->getPos();
  217. int3 posB = zoneB->getPos();
  218. if (posA.z == posB.z)
  219. {
  220. for (auto tile : tiles)
  221. {
  222. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  223. continue;
  224. foreach_neighbour (tile, [&guardPos, tile, &otherZoneTiles, this](int3 &pos)
  225. {
  226. //if (vstd::contains(otherZoneTiles, pos) && !this->isBlocked(pos))
  227. if (vstd::contains(otherZoneTiles, pos))
  228. guardPos = tile;
  229. });
  230. if (guardPos.valid())
  231. {
  232. setOccupied (guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  233. zoneA->addMonster (this, guardPos, connection.getGuardStrength(), false, true);
  234. //zones can make paths only in their own area
  235. zoneA->crunchPath (this, guardPos, posA, zoneA->getId(), zoneA->getFreePaths()); //make connection towards our zone center
  236. zoneB->crunchPath (this, guardPos, posB, zoneB->getId(), zoneB->getFreePaths()); //make connection towards other zone center
  237. break; //we're done with this connection
  238. }
  239. }
  240. }
  241. else //create subterranean gates between two zones
  242. {
  243. //find point on the path between zones
  244. float3 offset (posB.x - posA.x, posB.y - posA.y, 0);
  245. float distance = posB.dist2d(posA);
  246. vstd::amax (distance, 0.5f);
  247. offset /= distance; //get unit vector
  248. float3 vec (0, 0, 0);
  249. //use reduced size of underground zone - make sure gate does not stand on rock
  250. int3 tile = posA;
  251. int3 otherTile = tile;
  252. bool stop = false;
  253. while (!stop)
  254. {
  255. vec += offset; //this vector may extend beyond line between zone centers, in case they are directly over each other
  256. tile = posA + int3(vec.x, vec.y, 0);
  257. float distanceFromA = posA.dist2d(tile);
  258. float distanceFromB = posB.dist2d(tile);
  259. if (distanceFromA + distanceFromB > std::max<int>(zoneA->getSize() + zoneB->getSize(), distance))
  260. break; //we are too far away to ever connect
  261. //if zone is underground, gate must fit within its (reduced) radius
  262. if (distanceFromA > 5 && (!posA.z || distanceFromA < zoneA->getSize() - 3) &&
  263. distanceFromB > 5 && (!posB.z || distanceFromB < zoneB->getSize() - 3))
  264. {
  265. otherTile = tile;
  266. otherTile.z = posB.z;
  267. if (vstd::contains(tiles, tile) && vstd::contains(otherZoneTiles, otherTile))
  268. {
  269. bool withinZone = true;
  270. foreach_neighbour (tile, [&withinZone, &tiles](int3 &pos)
  271. {
  272. if (!vstd::contains(tiles, pos))
  273. withinZone = false;
  274. });
  275. foreach_neighbour (otherTile, [&withinZone, &otherZoneTiles](int3 &pos)
  276. {
  277. if (!vstd::contains(otherZoneTiles, pos))
  278. withinZone = false;
  279. });
  280. if (withinZone)
  281. {
  282. auto gate1 = new CGTeleport;
  283. gate1->ID = Obj::SUBTERRANEAN_GATE;
  284. gate1->subID = 0;
  285. zoneA->placeAndGuardObject(this, gate1, tile, connection.getGuardStrength());
  286. auto gate2 = new CGTeleport(*gate1);
  287. zoneB->placeAndGuardObject(this, gate2, otherTile, connection.getGuardStrength());
  288. stop = true; //we are done, go to next connection
  289. }
  290. }
  291. }
  292. }
  293. if (stop)
  294. continue;
  295. }
  296. if (!guardPos.valid())
  297. {
  298. auto teleport1 = new CGTeleport;
  299. teleport1->ID = Obj::MONOLITH_TWO_WAY;
  300. teleport1->subID = getNextMonlithIndex();
  301. auto teleport2 = new CGTeleport(*teleport1);
  302. zoneA->addRequiredObject (teleport1, connection.getGuardStrength());
  303. zoneB->addRequiredObject (teleport2, connection.getGuardStrength());
  304. }
  305. }
  306. }
  307. void CMapGenerator::addHeaderInfo()
  308. {
  309. map->version = EMapFormat::SOD;
  310. map->width = mapGenOptions->getWidth();
  311. map->height = mapGenOptions->getHeight();
  312. map->twoLevel = mapGenOptions->getHasTwoLevels();
  313. map->name = VLC->generaltexth->allTexts[740];
  314. map->description = getMapDescription();
  315. map->difficulty = 1;
  316. addPlayerInfo();
  317. }
  318. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  319. {
  320. return zones;
  321. }
  322. bool CMapGenerator::isBlocked(const int3 &tile) const
  323. {
  324. if (!map->isInTheMap(tile))
  325. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  326. return tiles[tile.x][tile.y][tile.z].isBlocked();
  327. }
  328. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  329. {
  330. if (!map->isInTheMap(tile))
  331. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  332. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  333. }
  334. bool CMapGenerator::isPossible(const int3 &tile) const
  335. {
  336. if (!map->isInTheMap(tile))
  337. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  338. return tiles[tile.x][tile.y][tile.z].isPossible();
  339. }
  340. bool CMapGenerator::isFree(const int3 &tile) const
  341. {
  342. if (!map->isInTheMap(tile))
  343. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  344. return tiles[tile.x][tile.y][tile.z].isFree();
  345. }
  346. bool CMapGenerator::isUsed(const int3 &tile) const
  347. {
  348. if (!map->isInTheMap(tile))
  349. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  350. return tiles[tile.x][tile.y][tile.z].isUsed();
  351. }
  352. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  353. {
  354. if (!map->isInTheMap(tile))
  355. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  356. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  357. }
  358. CTileInfo CMapGenerator::getTile(const int3& tile) const
  359. {
  360. if (!map->isInTheMap(tile))
  361. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  362. return tiles[tile.x][tile.y][tile.z];
  363. }
  364. void CMapGenerator::setNearestObjectDistance(int3 &tile, int value)
  365. {
  366. if (!map->isInTheMap(tile))
  367. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  368. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  369. }
  370. int CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  371. {
  372. if (!map->isInTheMap(tile))
  373. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile));
  374. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  375. }
  376. int CMapGenerator::getNextMonlithIndex()
  377. {
  378. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  379. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  380. else
  381. return monolithIndex++;
  382. }
  383. void CMapGenerator::registerZone (TFaction faction)
  384. {
  385. zonesPerFaction[faction]++;
  386. zonesTotal++;
  387. }
  388. ui32 CMapGenerator::getZoneCount(TFaction faction)
  389. {
  390. return zonesPerFaction[faction];
  391. }
  392. ui32 CMapGenerator::getTotalZoneCount() const
  393. {
  394. return zonesTotal;
  395. }