CMapGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. * CMapGenerator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CMapGenerator.h"
  12. #include "../mapping/CMap.h"
  13. #include "../VCMI_Lib.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../mapping/CMapEditManager.h"
  16. #include "../CTownHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "CZonePlacer.h"
  20. #include "CRmgTemplateZone.h"
  21. #include "../mapObjects/CObjectClassesHandler.h"
  22. static const int3 dirs4[] = {int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0)};
  23. static const int3 dirsDiagonal[] = { int3(1,1,0),int3(1,-1,0),int3(-1,1,0),int3(-1,-1,0) };
  24. void CMapGenerator::foreach_neighbour(const int3 &pos, std::function<void(int3& pos)> foo)
  25. {
  26. for(const int3 &dir : int3::getDirs())
  27. {
  28. int3 n = pos + dir;
  29. /*important notice: perform any translation before this function is called,
  30. so the actual map position is checked*/
  31. if(map->isInTheMap(n))
  32. foo(n);
  33. }
  34. }
  35. void CMapGenerator::foreachDirectNeighbour(const int3& pos, std::function<void(int3& pos)> foo)
  36. {
  37. for(const int3 &dir : dirs4)
  38. {
  39. int3 n = pos + dir;
  40. if(map->isInTheMap(n))
  41. foo(n);
  42. }
  43. }
  44. void CMapGenerator::foreachDiagonaltNeighbour(const int3& pos, std::function<void(int3& pos)> foo)
  45. {
  46. for (const int3 &dir : dirsDiagonal)
  47. {
  48. int3 n = pos + dir;
  49. if (map->isInTheMap(n))
  50. foo(n);
  51. }
  52. }
  53. CMapGenerator::CMapGenerator() :
  54. mapGenOptions(nullptr), randomSeed(0), editManager(nullptr),
  55. zonesTotal(0), tiles(nullptr), prisonsRemaining(0),
  56. monolithIndex(0)
  57. {
  58. }
  59. void CMapGenerator::initTiles()
  60. {
  61. map->initTerrain();
  62. int width = map->width;
  63. int height = map->height;
  64. int level = map->twoLevel ? 2 : 1;
  65. tiles = new CTileInfo**[width];
  66. for (int i = 0; i < width; ++i)
  67. {
  68. tiles[i] = new CTileInfo*[height];
  69. for (int j = 0; j < height; ++j)
  70. {
  71. tiles[i][j] = new CTileInfo[level];
  72. }
  73. }
  74. zoneColouring.resize(boost::extents[map->twoLevel ? 2 : 1][map->width][map->height]);
  75. }
  76. CMapGenerator::~CMapGenerator()
  77. {
  78. if (tiles)
  79. {
  80. int width = mapGenOptions->getWidth();
  81. int height = mapGenOptions->getHeight();
  82. for (int i=0; i < width; i++)
  83. {
  84. for(int j=0; j < height; j++)
  85. {
  86. delete [] tiles[i][j];
  87. }
  88. delete [] tiles[i];
  89. }
  90. delete [] tiles;
  91. }
  92. }
  93. void CMapGenerator::initPrisonsRemaining()
  94. {
  95. prisonsRemaining = 0;
  96. for (auto isAllowed : map->allowedHeroes)
  97. {
  98. if (isAllowed)
  99. prisonsRemaining++;
  100. }
  101. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions->getPlayerCount()); //so at least 16 heroes will be available for every player
  102. }
  103. void CMapGenerator::initQuestArtsRemaining()
  104. {
  105. for (auto art : VLC->arth->artifacts)
  106. {
  107. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->id) && art->constituentOf.empty()) //don't use parts of combined artifacts
  108. questArtifacts.push_back(art->id);
  109. }
  110. }
  111. std::unique_ptr<CMap> CMapGenerator::generate(CMapGenOptions * mapGenOptions, int randomSeed)
  112. {
  113. this->mapGenOptions = mapGenOptions;
  114. this->randomSeed = randomSeed;
  115. assert(mapGenOptions);
  116. rand.setSeed(this->randomSeed);
  117. mapGenOptions->finalize(rand);
  118. map = make_unique<CMap>();
  119. editManager = map->getEditManager();
  120. try
  121. {
  122. editManager->getUndoManager().setUndoRedoLimit(0);
  123. //FIXME: somehow mapGenOption is nullptr at this point :?
  124. addHeaderInfo();
  125. initTiles();
  126. initPrisonsRemaining();
  127. initQuestArtsRemaining();
  128. genZones();
  129. map->calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  130. fillZones();
  131. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  132. zones.clear();
  133. }
  134. catch (rmgException &e)
  135. {
  136. logGlobal->error("Random map generation received exception: %s", e.what());
  137. }
  138. return std::move(map);
  139. }
  140. std::string CMapGenerator::getMapDescription() const
  141. {
  142. assert(mapGenOptions);
  143. assert(map);
  144. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  145. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  146. int monsterStrengthIndex = mapGenOptions->getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  147. const auto * mapTemplate = mapGenOptions->getMapTemplate();
  148. if(!mapTemplate)
  149. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  150. std::stringstream ss;
  151. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  152. ", levels %s, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  153. randomSeed % map->width % map->height % (map->twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions->getPlayerCount()) %
  154. static_cast<int>(mapGenOptions->getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions->getWaterContent()] %
  155. monsterStrengthStr[monsterStrengthIndex]);
  156. for(const auto & pair : mapGenOptions->getPlayersSettings())
  157. {
  158. const auto & pSettings = pair.second;
  159. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  160. {
  161. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  162. }
  163. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  164. {
  165. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  166. << " town choice is " << VLC->townh->factions[pSettings.getStartingTown()]->name;
  167. }
  168. }
  169. return ss.str();
  170. }
  171. void CMapGenerator::addPlayerInfo()
  172. {
  173. // Calculate which team numbers exist
  174. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  175. std::array<std::list<int>, 2> teamNumbers;
  176. int teamOffset = 0;
  177. int playerCount = 0;
  178. int teamCount = 0;
  179. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  180. {
  181. if (i == CPHUMAN)
  182. {
  183. playerCount = mapGenOptions->getPlayerCount();
  184. teamCount = mapGenOptions->getTeamCount();
  185. }
  186. else
  187. {
  188. playerCount = mapGenOptions->getCompOnlyPlayerCount();
  189. teamCount = mapGenOptions->getCompOnlyTeamCount();
  190. }
  191. if(playerCount == 0)
  192. {
  193. continue;
  194. }
  195. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  196. int teamCountNorm = teamCount;
  197. if(teamCountNorm == 0)
  198. {
  199. teamCountNorm = playerCount;
  200. }
  201. for(int j = 0; j < teamCountNorm; ++j)
  202. {
  203. for(int k = 0; k < playersPerTeam; ++k)
  204. {
  205. teamNumbers[i].push_back(j + teamOffset);
  206. }
  207. }
  208. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  209. {
  210. teamNumbers[i].push_back(j + teamOffset);
  211. }
  212. teamOffset += teamCountNorm;
  213. }
  214. // Team numbers are assigned randomly to every player
  215. //TODO: allow customize teams in rmg template
  216. for(const auto & pair : mapGenOptions->getPlayersSettings())
  217. {
  218. const auto & pSettings = pair.second;
  219. PlayerInfo player;
  220. player.canComputerPlay = true;
  221. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  222. if (j == CPHUMAN)
  223. {
  224. player.canHumanPlay = true;
  225. }
  226. if (teamNumbers[j].empty())
  227. {
  228. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  229. assert (teamNumbers[j].size());
  230. }
  231. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  232. player.team = TeamID(*itTeam);
  233. teamNumbers[j].erase(itTeam);
  234. map->players[pSettings.getColor().getNum()] = player;
  235. }
  236. map->howManyTeams = (mapGenOptions->getTeamCount() == 0 ? mapGenOptions->getPlayerCount() : mapGenOptions->getTeamCount())
  237. + (mapGenOptions->getCompOnlyTeamCount() == 0 ? mapGenOptions->getCompOnlyPlayerCount() : mapGenOptions->getCompOnlyTeamCount());
  238. }
  239. void CMapGenerator::genZones()
  240. {
  241. editManager->clearTerrain(&rand);
  242. editManager->getTerrainSelection().selectRange(MapRect(int3(0, 0, 0), mapGenOptions->getWidth(), mapGenOptions->getHeight()));
  243. editManager->drawTerrain(ETerrainType::GRASS, &rand);
  244. auto tmpl = mapGenOptions->getMapTemplate();
  245. zones.clear();
  246. for(const auto & option : tmpl->getZones())
  247. {
  248. auto zone = std::make_shared<CRmgTemplateZone>();
  249. zone->setOptions(option.second.get());
  250. zones[zone->getId()] = zone;
  251. //todo: move to CRmgTemplateZone constructor
  252. zone->setGenPtr(this);//immediately set gen pointer before taking any actions on zones
  253. }
  254. CZonePlacer placer(this);
  255. placer.placeZones(mapGenOptions, &rand);
  256. placer.assignZones(mapGenOptions);
  257. logGlobal->info("Zones generated successfully");
  258. }
  259. void CMapGenerator::fillZones()
  260. {
  261. //init native town count with 0
  262. for (auto faction : VLC->townh->getAllowedFactions())
  263. zonesPerFaction[faction] = 0;
  264. findZonesForQuestArts();
  265. logGlobal->info("Started filling zones");
  266. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  267. //place main town in the middle
  268. for (auto it : zones)
  269. it.second->initTownType();
  270. //make sure there are some free tiles in the zone
  271. for (auto it : zones)
  272. it.second->initFreeTiles();
  273. createDirectConnections(); //direct
  274. //make sure all connections are passable before creating borders
  275. for (auto it : zones)
  276. it.second->createBorder(); //once direct connections are done
  277. createConnections2(); //subterranean gates and monoliths
  278. std::vector<std::shared_ptr<CRmgTemplateZone>> treasureZones;
  279. for (auto it : zones)
  280. {
  281. it.second->fill();
  282. if (it.second->getType() == ETemplateZoneType::TREASURE)
  283. treasureZones.push_back(it.second);
  284. }
  285. //set apriopriate free/occupied tiles, including blocked underground rock
  286. createObstaclesCommon1();
  287. //set back original terrain for underground zones
  288. for (auto it : zones)
  289. it.second->createObstacles1();
  290. createObstaclesCommon2();
  291. //place actual obstacles matching zone terrain
  292. for (auto it : zones)
  293. {
  294. it.second->createObstacles2();
  295. }
  296. #define PRINT_MAP_BEFORE_ROADS false
  297. if (PRINT_MAP_BEFORE_ROADS) //enable to debug
  298. {
  299. std::ofstream out("road debug");
  300. int levels = map->twoLevel ? 2 : 1;
  301. int width = map->width;
  302. int height = map->height;
  303. for (int k = 0; k < levels; k++)
  304. {
  305. for (int j = 0; j<height; j++)
  306. {
  307. for (int i = 0; i<width; i++)
  308. {
  309. char t = '?';
  310. switch (getTile(int3(i, j, k)).getTileType())
  311. {
  312. case ETileType::FREE:
  313. t = ' '; break;
  314. case ETileType::BLOCKED:
  315. t = '#'; break;
  316. case ETileType::POSSIBLE:
  317. t = '-'; break;
  318. case ETileType::USED:
  319. t = 'O'; break;
  320. }
  321. out << t;
  322. }
  323. out << std::endl;
  324. }
  325. out << std::endl;
  326. }
  327. out << std::endl;
  328. }
  329. for (auto it : zones)
  330. {
  331. it.second->connectRoads(); //draw roads after everything else has been placed
  332. }
  333. //find place for Grail
  334. if (treasureZones.empty())
  335. {
  336. for (auto it : zones)
  337. treasureZones.push_back(it.second);
  338. }
  339. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  340. map->grailPos = *RandomGeneratorUtil::nextItem(*grailZone->getFreePaths(), rand);
  341. logGlobal->info("Zones filled successfully");
  342. }
  343. void CMapGenerator::createObstaclesCommon1()
  344. {
  345. if (map->twoLevel) //underground
  346. {
  347. //negative approach - create rock tiles first, then make sure all accessible tiles have no rock
  348. std::vector<int3> rockTiles;
  349. for (int x = 0; x < map->width; x++)
  350. {
  351. for (int y = 0; y < map->height; y++)
  352. {
  353. int3 tile(x, y, 1);
  354. if (shouldBeBlocked(tile))
  355. {
  356. rockTiles.push_back(tile);
  357. }
  358. }
  359. }
  360. editManager->getTerrainSelection().setSelection(rockTiles);
  361. editManager->drawTerrain(ETerrainType::ROCK, &rand);
  362. }
  363. }
  364. void CMapGenerator::createObstaclesCommon2()
  365. {
  366. if (map->twoLevel)
  367. {
  368. //finally mark rock tiles as occupied, spawn no obstacles there
  369. for (int x = 0; x < map->width; x++)
  370. {
  371. for (int y = 0; y < map->height; y++)
  372. {
  373. int3 tile(x, y, 1);
  374. if (map->getTile(tile).terType == ETerrainType::ROCK)
  375. {
  376. setOccupied(tile, ETileType::USED);
  377. }
  378. }
  379. }
  380. }
  381. //tighten obstacles to improve visuals
  382. for (int i = 0; i < 3; ++i)
  383. {
  384. int blockedTiles = 0;
  385. int freeTiles = 0;
  386. for (int z = 0; z < (map->twoLevel ? 2 : 1); z++)
  387. {
  388. for (int x = 0; x < map->width; x++)
  389. {
  390. for (int y = 0; y < map->height; y++)
  391. {
  392. int3 tile(x, y, z);
  393. if (!isPossible(tile)) //only possible tiles can change
  394. continue;
  395. int blockedNeighbours = 0;
  396. int freeNeighbours = 0;
  397. foreach_neighbour(tile, [this, &blockedNeighbours, &freeNeighbours](int3 &pos)
  398. {
  399. if (this->isBlocked(pos))
  400. blockedNeighbours++;
  401. if (this->isFree(pos))
  402. freeNeighbours++;
  403. });
  404. if (blockedNeighbours > 4)
  405. {
  406. setOccupied(tile, ETileType::BLOCKED);
  407. blockedTiles++;
  408. }
  409. else if (freeNeighbours > 4)
  410. {
  411. setOccupied(tile, ETileType::FREE);
  412. freeTiles++;
  413. }
  414. }
  415. }
  416. }
  417. logGlobal->trace("Set %d tiles to BLOCKED and %d tiles to FREE", blockedTiles, freeTiles);
  418. }
  419. }
  420. void CMapGenerator::findZonesForQuestArts()
  421. {
  422. //we want to place arties in zones that were not yet filled (higher index)
  423. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  424. {
  425. auto zoneA = zones[connection.getZoneA()];
  426. auto zoneB = zones[connection.getZoneB()];
  427. if (zoneA->getId() > zoneB->getId())
  428. {
  429. zoneB->setQuestArtZone(zoneA);
  430. }
  431. else if (zoneA->getId() < zoneB->getId())
  432. {
  433. zoneA->setQuestArtZone(zoneB);
  434. }
  435. }
  436. }
  437. void CMapGenerator::createDirectConnections()
  438. {
  439. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  440. {
  441. auto zoneA = zones[connection.getZoneA()];
  442. auto zoneB = zones[connection.getZoneB()];
  443. //rearrange tiles in random order
  444. auto tilesCopy = zoneA->getTileInfo();
  445. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  446. int3 guardPos(-1,-1,-1);
  447. auto otherZoneTiles = zoneB->getTileInfo();
  448. int3 posA = zoneA->getPos();
  449. int3 posB = zoneB->getPos();
  450. // auto zoneAid = zoneA->getId();
  451. auto zoneBid = zoneB->getId();
  452. if (posA.z == posB.z)
  453. {
  454. std::vector<int3> middleTiles;
  455. for (auto tile : tilesCopy)
  456. {
  457. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  458. continue;
  459. foreachDirectNeighbour(tile, [tile, &middleTiles, this, zoneBid](int3 & pos) //must be direct since paths also also generated between direct neighbours
  460. {
  461. if(getZoneID(pos) == zoneBid)
  462. middleTiles.push_back(tile);
  463. });
  464. }
  465. //find tiles with minimum manhattan distance from center of the mass of zone border
  466. size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1;
  467. int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0));
  468. middleTile.x /= (si32)tilesCount;
  469. middleTile.y /= (si32)tilesCount;
  470. middleTile.z /= (si32)tilesCount; //TODO: implement division operator for int3?
  471. boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool
  472. {
  473. //choose tiles with both corrdinates in the middle
  474. return lhs.mandist2d(middleTile) < rhs.mandist2d(middleTile);
  475. });
  476. //remove 1/4 tiles from each side - path should cross zone borders at smooth angle
  477. size_t removedCount = tilesCount / 4; //rounded down
  478. middleTiles.erase(middleTiles.end() - removedCount, middleTiles.end());
  479. middleTiles.erase(middleTiles.begin(), middleTiles.begin() + removedCount);
  480. RandomGeneratorUtil::randomShuffle(middleTiles, rand);
  481. for (auto tile : middleTiles)
  482. {
  483. guardPos = tile;
  484. if (guardPos.valid())
  485. {
  486. //zones can make paths only in their own area
  487. zoneA->connectWithCenter(guardPos, true);
  488. zoneB->connectWithCenter(guardPos, true);
  489. bool monsterPresent = zoneA->addMonster(guardPos, connection.getGuardStrength(), false, true);
  490. zoneB->updateDistances(guardPos); //place next objects away from guard in both zones
  491. //set free tile only after connection is made to the center of the zone
  492. if (!monsterPresent)
  493. setOccupied(guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  494. zoneA->addRoadNode(guardPos);
  495. zoneB->addRoadNode(guardPos);
  496. break; //we're done with this connection
  497. }
  498. }
  499. }
  500. if (!guardPos.valid())
  501. connectionsLeft.push_back(connection);
  502. }
  503. }
  504. void CMapGenerator::createConnections2()
  505. {
  506. for (auto & connection : connectionsLeft)
  507. {
  508. auto zoneA = zones[connection.getZoneA()];
  509. auto zoneB = zones[connection.getZoneB()];
  510. int3 guardPos(-1, -1, -1);
  511. int3 posA = zoneA->getPos();
  512. int3 posB = zoneB->getPos();
  513. auto strength = connection.getGuardStrength();
  514. if (posA.z != posB.z) //try to place subterranean gates
  515. {
  516. auto sgt = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0)->getTemplates().front();
  517. auto tilesBlockedByObject = sgt.getBlockedOffsets();
  518. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  519. auto gate1 = factory->create(ObjectTemplate());
  520. auto gate2 = factory->create(ObjectTemplate());
  521. while (!guardPos.valid())
  522. {
  523. bool continueOuterLoop = false;
  524. //find common tiles for both zones
  525. auto tileSetA = zoneA->getPossibleTiles(),
  526. tileSetB = zoneB->getPossibleTiles();
  527. std::vector<int3> tilesA(tileSetA.begin(), tileSetA.end()),
  528. tilesB(tileSetB.begin(), tileSetB.end());
  529. std::vector<int3> commonTiles;
  530. auto lambda = [](const int3 & lhs, const int3 & rhs) -> bool
  531. {
  532. //https://stackoverflow.com/questions/45966807/c-invalid-comparator-assert
  533. return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y); //ignore z coordinate
  534. };
  535. //required for set_intersection
  536. boost::sort(tilesA, lambda);
  537. boost::sort(tilesB, lambda);
  538. boost::set_intersection(tilesA, tilesB, std::back_inserter(commonTiles), lambda);
  539. vstd::erase_if(commonTiles, [](const int3 &tile) -> bool
  540. {
  541. return (!tile.x) || (!tile.y); //gates shouldn't go outside map (x = 0) and look bad at the very top (y = 0)
  542. });
  543. if (commonTiles.empty())
  544. break; //nothing more to do
  545. boost::sort(commonTiles, [posA, posB](const int3 &lhs, const int3 &rhs) -> bool
  546. {
  547. //choose tiles which are equidistant to zone centers
  548. return (std::abs<double>(posA.dist2dSQ(lhs) - posB.dist2dSQ(lhs)) < std::abs<double>((posA.dist2dSQ(rhs) - posB.dist2dSQ(rhs))));
  549. });
  550. for (auto tile : commonTiles)
  551. {
  552. tile.z = posA.z;
  553. int3 otherTile = tile;
  554. otherTile.z = posB.z;
  555. float distanceFromA = static_cast<float>(posA.dist2d(tile));
  556. float distanceFromB = static_cast<float>(posB.dist2d(otherTile));
  557. if (distanceFromA > 5 && distanceFromB > 5)
  558. {
  559. if (zoneA->areAllTilesAvailable(gate1, tile, tilesBlockedByObject) &&
  560. zoneB->areAllTilesAvailable(gate2, otherTile, tilesBlockedByObject))
  561. {
  562. if (zoneA->getAccessibleOffset(sgt, tile).valid() && zoneB->getAccessibleOffset(sgt, otherTile).valid())
  563. {
  564. EObjectPlacingResult::EObjectPlacingResult result1 = zoneA->tryToPlaceObjectAndConnectToPath(gate1, tile);
  565. EObjectPlacingResult::EObjectPlacingResult result2 = zoneB->tryToPlaceObjectAndConnectToPath(gate2, otherTile);
  566. if ((result1 == EObjectPlacingResult::SUCCESS) && (result2 == EObjectPlacingResult::SUCCESS))
  567. {
  568. zoneA->placeObject(gate1, tile);
  569. zoneA->guardObject(gate1, strength, true, true);
  570. zoneB->placeObject(gate2, otherTile);
  571. zoneB->guardObject(gate2, strength, true, true);
  572. guardPos = tile; //set to break the loop
  573. break;
  574. }
  575. else if ((result1 == EObjectPlacingResult::SEALED_OFF) || (result2 == EObjectPlacingResult::SEALED_OFF))
  576. {
  577. //sealed-off tiles were blocked, exit inner loop and get another tile set
  578. continueOuterLoop = true;
  579. break;
  580. }
  581. else
  582. continue; //try with another position
  583. }
  584. }
  585. }
  586. }
  587. if (!continueOuterLoop) //we didn't find ANY tile - break outer loop
  588. break;
  589. }
  590. if (!guardPos.valid()) //cleanup? is this safe / enough?
  591. {
  592. delete gate1;
  593. delete gate2;
  594. }
  595. }
  596. if (!guardPos.valid())
  597. {
  598. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, getNextMonlithIndex());
  599. auto teleport1 = factory->create(ObjectTemplate());
  600. auto teleport2 = factory->create(ObjectTemplate());
  601. zoneA->addRequiredObject(teleport1, strength);
  602. zoneB->addRequiredObject(teleport2, strength);
  603. }
  604. }
  605. }
  606. void CMapGenerator::addHeaderInfo()
  607. {
  608. map->version = EMapFormat::VCMI;
  609. map->width = mapGenOptions->getWidth();
  610. map->height = mapGenOptions->getHeight();
  611. map->twoLevel = mapGenOptions->getHasTwoLevels();
  612. map->name = VLC->generaltexth->allTexts[740];
  613. map->description = getMapDescription();
  614. map->difficulty = 1;
  615. addPlayerInfo();
  616. }
  617. void CMapGenerator::checkIsOnMap(const int3& tile) const
  618. {
  619. if (!map->isInTheMap(tile))
  620. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile.toString()));
  621. }
  622. CMapGenerator::Zones & CMapGenerator::getZones()
  623. {
  624. return zones;
  625. }
  626. bool CMapGenerator::isBlocked(const int3 &tile) const
  627. {
  628. checkIsOnMap(tile);
  629. return tiles[tile.x][tile.y][tile.z].isBlocked();
  630. }
  631. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  632. {
  633. checkIsOnMap(tile);
  634. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  635. }
  636. bool CMapGenerator::isPossible(const int3 &tile) const
  637. {
  638. checkIsOnMap(tile);
  639. return tiles[tile.x][tile.y][tile.z].isPossible();
  640. }
  641. bool CMapGenerator::isFree(const int3 &tile) const
  642. {
  643. checkIsOnMap(tile);
  644. return tiles[tile.x][tile.y][tile.z].isFree();
  645. }
  646. bool CMapGenerator::isUsed(const int3 &tile) const
  647. {
  648. checkIsOnMap(tile);
  649. return tiles[tile.x][tile.y][tile.z].isUsed();
  650. }
  651. bool CMapGenerator::isRoad(const int3& tile) const
  652. {
  653. checkIsOnMap(tile);
  654. return tiles[tile.x][tile.y][tile.z].isRoad();
  655. }
  656. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  657. {
  658. checkIsOnMap(tile);
  659. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  660. }
  661. void CMapGenerator::setRoad(const int3& tile, ERoadType::ERoadType roadType)
  662. {
  663. checkIsOnMap(tile);
  664. tiles[tile.x][tile.y][tile.z].setRoadType(roadType);
  665. }
  666. CTileInfo CMapGenerator::getTile(const int3& tile) const
  667. {
  668. checkIsOnMap(tile);
  669. return tiles[tile.x][tile.y][tile.z];
  670. }
  671. TRmgTemplateZoneId CMapGenerator::getZoneID(const int3& tile) const
  672. {
  673. checkIsOnMap(tile);
  674. return zoneColouring[tile.z][tile.x][tile.y];
  675. }
  676. void CMapGenerator::setZoneID(const int3& tile, TRmgTemplateZoneId zid)
  677. {
  678. checkIsOnMap(tile);
  679. zoneColouring[tile.z][tile.x][tile.y] = zid;
  680. }
  681. bool CMapGenerator::isAllowedSpell(SpellID sid) const
  682. {
  683. assert(sid >= 0);
  684. if (sid < map->allowedSpell.size())
  685. {
  686. return map->allowedSpell[sid];
  687. }
  688. else
  689. return false;
  690. }
  691. void CMapGenerator::setNearestObjectDistance(int3 &tile, float value)
  692. {
  693. checkIsOnMap(tile);
  694. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  695. }
  696. float CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  697. {
  698. checkIsOnMap(tile);
  699. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  700. }
  701. int CMapGenerator::getNextMonlithIndex()
  702. {
  703. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  704. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  705. else
  706. return monolithIndex++;
  707. }
  708. int CMapGenerator::getPrisonsRemaning() const
  709. {
  710. return prisonsRemaining;
  711. }
  712. void CMapGenerator::decreasePrisonsRemaining()
  713. {
  714. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  715. }
  716. std::vector<ArtifactID> CMapGenerator::getQuestArtsRemaning() const
  717. {
  718. return questArtifacts;
  719. }
  720. void CMapGenerator::banQuestArt(ArtifactID id)
  721. {
  722. map->allowedArtifact[id] = false;
  723. vstd::erase_if_present (questArtifacts, id);
  724. }
  725. void CMapGenerator::registerZone (TFaction faction)
  726. {
  727. zonesPerFaction[faction]++;
  728. zonesTotal++;
  729. }
  730. ui32 CMapGenerator::getZoneCount(TFaction faction)
  731. {
  732. return zonesPerFaction[faction];
  733. }
  734. ui32 CMapGenerator::getTotalZoneCount() const
  735. {
  736. return zonesTotal;
  737. }