CMapGenerator.cpp 23 KB

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