CMapGenerator.cpp 14 KB

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