CMapGenerator.cpp 23 KB

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