CMapGenerator.cpp 15 KB

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