CMapGenerator.cpp 14 KB

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