CMapGenerator.cpp 14 KB

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