CMapGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. CZonePlacer placer(this);
  242. placer.placeZones(mapGenOptions, &rand);
  243. placer.assignZones(mapGenOptions);
  244. logGlobal->info("Zones generated successfully");
  245. }
  246. void CMapGenerator::fillZones()
  247. {
  248. //init native town count with 0
  249. for (auto faction : VLC->townh->getAllowedFactions())
  250. zonesPerFaction[faction] = 0;
  251. findZonesForQuestArts();
  252. logGlobal->info("Started filling zones");
  253. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  254. //place main town in the middle
  255. for (auto it : zones)
  256. it.second->initTownType(this);
  257. //make sure there are some free tiles in the zone
  258. for (auto it : zones)
  259. it.second->initFreeTiles(this);
  260. createDirectConnections(); //direct
  261. //make sure all connections are passable before creating borders
  262. for (auto it : zones)
  263. it.second->createBorder(this); //once direct connections are done
  264. createConnections2(); //subterranean gates and monoliths
  265. std::vector<CRmgTemplateZone*> treasureZones;
  266. for (auto it : zones)
  267. {
  268. it.second->fill(this);
  269. if (it.second->getType() == ETemplateZoneType::TREASURE)
  270. treasureZones.push_back(it.second);
  271. }
  272. //set apriopriate free/occupied tiles, including blocked underground rock
  273. createObstaclesCommon1();
  274. //set back original terrain for underground zones
  275. for (auto it : zones)
  276. it.second->createObstacles1(this);
  277. createObstaclesCommon2();
  278. //place actual obstacles matching zone terrain
  279. for (auto it : zones)
  280. {
  281. it.second->createObstacles2(this);
  282. }
  283. #define PRINT_MAP_BEFORE_ROADS false
  284. if (PRINT_MAP_BEFORE_ROADS) //enable to debug
  285. {
  286. std::ofstream out("road debug");
  287. int levels = map->twoLevel ? 2 : 1;
  288. int width = map->width;
  289. int height = map->height;
  290. for (int k = 0; k < levels; k++)
  291. {
  292. for (int j = 0; j<height; j++)
  293. {
  294. for (int i = 0; i<width; i++)
  295. {
  296. char t = '?';
  297. switch (getTile(int3(i, j, k)).getTileType())
  298. {
  299. case ETileType::FREE:
  300. t = ' '; break;
  301. case ETileType::BLOCKED:
  302. t = '#'; break;
  303. case ETileType::POSSIBLE:
  304. t = '-'; break;
  305. case ETileType::USED:
  306. t = 'O'; break;
  307. }
  308. out << t;
  309. }
  310. out << std::endl;
  311. }
  312. out << std::endl;
  313. }
  314. out << std::endl;
  315. }
  316. for (auto it : zones)
  317. {
  318. it.second->connectRoads(this); //draw roads after everything else has been placed
  319. }
  320. //find place for Grail
  321. if (treasureZones.empty())
  322. {
  323. for (auto it : zones)
  324. treasureZones.push_back(it.second);
  325. }
  326. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  327. map->grailPos = *RandomGeneratorUtil::nextItem(*grailZone->getFreePaths(), rand);
  328. logGlobal->info("Zones filled successfully");
  329. }
  330. void CMapGenerator::createObstaclesCommon1()
  331. {
  332. if (map->twoLevel) //underground
  333. {
  334. //negative approach - create rock tiles first, then make sure all accessible tiles have no rock
  335. std::vector<int3> rockTiles;
  336. for (int x = 0; x < map->width; x++)
  337. {
  338. for (int y = 0; y < map->height; y++)
  339. {
  340. int3 tile(x, y, 1);
  341. if (shouldBeBlocked(tile))
  342. {
  343. rockTiles.push_back(tile);
  344. }
  345. }
  346. }
  347. editManager->getTerrainSelection().setSelection(rockTiles);
  348. editManager->drawTerrain(ETerrainType::ROCK, &rand);
  349. }
  350. }
  351. void CMapGenerator::createObstaclesCommon2()
  352. {
  353. if (map->twoLevel)
  354. {
  355. //finally mark rock tiles as occupied, spawn no obstacles there
  356. for (int x = 0; x < map->width; x++)
  357. {
  358. for (int y = 0; y < map->height; y++)
  359. {
  360. int3 tile(x, y, 1);
  361. if (map->getTile(tile).terType == ETerrainType::ROCK)
  362. {
  363. setOccupied(tile, ETileType::USED);
  364. }
  365. }
  366. }
  367. }
  368. //tighten obstacles to improve visuals
  369. for (int i = 0; i < 3; ++i)
  370. {
  371. int blockedTiles = 0;
  372. int freeTiles = 0;
  373. for (int z = 0; z < (map->twoLevel ? 2 : 1); z++)
  374. {
  375. for (int x = 0; x < map->width; x++)
  376. {
  377. for (int y = 0; y < map->height; y++)
  378. {
  379. int3 tile(x, y, z);
  380. if (!isPossible(tile)) //only possible tiles can change
  381. continue;
  382. int blockedNeighbours = 0;
  383. int freeNeighbours = 0;
  384. foreach_neighbour(tile, [this, &blockedNeighbours, &freeNeighbours](int3 &pos)
  385. {
  386. if (this->isBlocked(pos))
  387. blockedNeighbours++;
  388. if (this->isFree(pos))
  389. freeNeighbours++;
  390. });
  391. if (blockedNeighbours > 4)
  392. {
  393. setOccupied(tile, ETileType::BLOCKED);
  394. blockedTiles++;
  395. }
  396. else if (freeNeighbours > 4)
  397. {
  398. setOccupied(tile, ETileType::FREE);
  399. freeTiles++;
  400. }
  401. }
  402. }
  403. }
  404. logGlobal->trace("Set %d tiles to BLOCKED and %d tiles to FREE", blockedTiles, freeTiles);
  405. }
  406. }
  407. void CMapGenerator::findZonesForQuestArts()
  408. {
  409. //we want to place arties in zones that were not yet filled (higher index)
  410. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  411. {
  412. auto zoneA = connection.getZoneA();
  413. auto zoneB = connection.getZoneB();
  414. if (zoneA->getId() > zoneB->getId())
  415. {
  416. zoneB->setQuestArtZone(zoneA);
  417. }
  418. else if (zoneA->getId() < zoneB->getId())
  419. {
  420. zoneA->setQuestArtZone(zoneB);
  421. }
  422. }
  423. }
  424. void CMapGenerator::createDirectConnections()
  425. {
  426. for (auto connection : mapGenOptions->getMapTemplate()->getConnections())
  427. {
  428. auto zoneA = connection.getZoneA();
  429. auto zoneB = connection.getZoneB();
  430. //rearrange tiles in random order
  431. auto tilesCopy = zoneA->getTileInfo();
  432. std::vector<int3> tiles(tilesCopy.begin(), tilesCopy.end());
  433. int3 guardPos(-1,-1,-1);
  434. auto otherZoneTiles = zoneB->getTileInfo();
  435. int3 posA = zoneA->getPos();
  436. int3 posB = zoneB->getPos();
  437. // auto zoneAid = zoneA->getId();
  438. auto zoneBid = zoneB->getId();
  439. if (posA.z == posB.z)
  440. {
  441. std::vector<int3> middleTiles;
  442. for (auto tile : tilesCopy)
  443. {
  444. if (isBlocked(tile)) //tiles may be occupied by subterranean gates already placed
  445. continue;
  446. foreachDirectNeighbour (tile, [&guardPos, tile, &otherZoneTiles, &middleTiles, this, zoneBid](int3 &pos) //must be direct since paths also also generated between direct neighbours
  447. {
  448. if (getZoneID(pos) == zoneBid)
  449. middleTiles.push_back(tile);
  450. });
  451. }
  452. //find tiles with minimum manhattan distance from center of the mass of zone border
  453. size_t tilesCount = middleTiles.size() ? middleTiles.size() : 1;
  454. int3 middleTile = std::accumulate(middleTiles.begin(), middleTiles.end(), int3(0, 0, 0));
  455. middleTile.x /= tilesCount;
  456. middleTile.y /= tilesCount;
  457. middleTile.z /= tilesCount; //TODO: implement division operator for int3?
  458. boost::sort(middleTiles, [middleTile](const int3 &lhs, const int3 &rhs) -> bool
  459. {
  460. //choose tiles with both corrdinates in the middle
  461. return lhs.mandist2d(middleTile) < rhs.mandist2d(middleTile);
  462. });
  463. //remove 1/4 tiles from each side - path should cross zone borders at smooth angle
  464. size_t removedCount = tilesCount / 4; //rounded down
  465. middleTiles.erase(middleTiles.end() - removedCount, middleTiles.end());
  466. middleTiles.erase(middleTiles.begin(), middleTiles.begin() + removedCount);
  467. RandomGeneratorUtil::randomShuffle(middleTiles, rand);
  468. for (auto tile : middleTiles)
  469. {
  470. guardPos = tile;
  471. if (guardPos.valid())
  472. {
  473. //zones can make paths only in their own area
  474. zoneA->connectWithCenter(this, guardPos, true);
  475. zoneB->connectWithCenter(this, guardPos, true);
  476. bool monsterPresent = zoneA->addMonster(this, guardPos, connection.getGuardStrength(), false, true);
  477. zoneB->updateDistances(this, guardPos); //place next objects away from guard in both zones
  478. //set free tile only after connection is made to the center of the zone
  479. if (!monsterPresent)
  480. setOccupied(guardPos, ETileType::FREE); //just in case monster is too weak to spawn
  481. zoneA->addRoadNode(guardPos);
  482. zoneB->addRoadNode(guardPos);
  483. break; //we're done with this connection
  484. }
  485. }
  486. }
  487. if (!guardPos.valid())
  488. connectionsLeft.push_back(connection);
  489. }
  490. }
  491. void CMapGenerator::createConnections2()
  492. {
  493. for (auto & connection : connectionsLeft)
  494. {
  495. auto zoneA = connection.getZoneA();
  496. auto zoneB = connection.getZoneB();
  497. int3 guardPos(-1, -1, -1);
  498. int3 posA = zoneA->getPos();
  499. int3 posB = zoneB->getPos();
  500. auto strength = connection.getGuardStrength();
  501. if (posA.z != posB.z) //try to place subterranean gates
  502. {
  503. auto sgt = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0)->getTemplates().front();
  504. auto tilesBlockedByObject = sgt.getBlockedOffsets();
  505. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  506. auto gate1 = factory->create(ObjectTemplate());
  507. auto gate2 = factory->create(ObjectTemplate());
  508. while (!guardPos.valid())
  509. {
  510. bool continueOuterLoop = false;
  511. //find common tiles for both zones
  512. auto tileSetA = zoneA->getPossibleTiles(),
  513. tileSetB = zoneB->getPossibleTiles();
  514. std::vector<int3> tilesA(tileSetA.begin(), tileSetA.end()),
  515. tilesB(tileSetB.begin(), tileSetB.end());
  516. std::vector<int3> commonTiles;
  517. //required for set_intersection
  518. boost::sort(tilesA);
  519. boost::sort(tilesB);
  520. boost::set_intersection(tilesA, tilesB, std::back_inserter(commonTiles), [](const int3 &lhs, const int3 &rhs) -> bool
  521. {
  522. //ignore z coordinate
  523. if (lhs.x < rhs.x)
  524. return true;
  525. else
  526. return lhs.y < rhs.y;
  527. });
  528. vstd::erase_if(commonTiles, [](const int3 &tile) -> bool
  529. {
  530. return (!tile.x) || (!tile.y); //gates shouldn't go outside map (x = 0) and look bad at the very top (y = 0)
  531. });
  532. if (commonTiles.empty())
  533. break; //nothing more to do
  534. boost::sort(commonTiles, [posA, posB](const int3 &lhs, const int3 &rhs) -> bool
  535. {
  536. //choose tiles which are equidistant to zone centers
  537. return (std::abs<double>(posA.dist2dSQ(lhs) - posB.dist2dSQ(lhs)) < std::abs<double>((posA.dist2dSQ(rhs) - posB.dist2dSQ(rhs))));
  538. });
  539. for (auto tile : commonTiles)
  540. {
  541. tile.z = posA.z;
  542. int3 otherTile = tile;
  543. otherTile.z = posB.z;
  544. float distanceFromA = posA.dist2d(tile);
  545. float distanceFromB = posB.dist2d(otherTile);
  546. if (distanceFromA > 5 && distanceFromB > 5)
  547. {
  548. if (zoneA->areAllTilesAvailable(this, gate1, tile, tilesBlockedByObject) &&
  549. zoneB->areAllTilesAvailable(this, gate2, otherTile, tilesBlockedByObject))
  550. {
  551. if (zoneA->getAccessibleOffset(this, sgt, tile).valid() && zoneB->getAccessibleOffset(this, sgt, otherTile).valid())
  552. {
  553. EObjectPlacingResult::EObjectPlacingResult result1 = zoneA->tryToPlaceObjectAndConnectToPath(this, gate1, tile);
  554. EObjectPlacingResult::EObjectPlacingResult result2 = zoneB->tryToPlaceObjectAndConnectToPath(this, gate2, otherTile);
  555. if ((result1 == EObjectPlacingResult::SUCCESS) && (result2 == EObjectPlacingResult::SUCCESS))
  556. {
  557. zoneA->placeObject(this, gate1, tile);
  558. zoneA->guardObject(this, gate1, strength, true, true);
  559. zoneB->placeObject(this, gate2, otherTile);
  560. zoneB->guardObject(this, gate2, strength, true, true);
  561. guardPos = tile; //set to break the loop
  562. break;
  563. }
  564. else if ((result1 == EObjectPlacingResult::SEALED_OFF) || (result2 == EObjectPlacingResult::SEALED_OFF))
  565. {
  566. //sealed-off tiles were blocked, exit inner loop and get another tile set
  567. continueOuterLoop = true;
  568. break;
  569. }
  570. else
  571. continue; //try with another position
  572. }
  573. }
  574. }
  575. }
  576. if (!continueOuterLoop) //we didn't find ANY tile - break outer loop
  577. break;
  578. }
  579. if (!guardPos.valid()) //cleanup? is this safe / enough?
  580. {
  581. delete gate1;
  582. delete gate2;
  583. }
  584. }
  585. if (!guardPos.valid())
  586. {
  587. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, getNextMonlithIndex());
  588. auto teleport1 = factory->create(ObjectTemplate());
  589. auto teleport2 = factory->create(ObjectTemplate());
  590. zoneA->addRequiredObject(teleport1, strength);
  591. zoneB->addRequiredObject(teleport2, strength);
  592. }
  593. }
  594. }
  595. void CMapGenerator::addHeaderInfo()
  596. {
  597. map->version = EMapFormat::VCMI;
  598. map->width = mapGenOptions->getWidth();
  599. map->height = mapGenOptions->getHeight();
  600. map->twoLevel = mapGenOptions->getHasTwoLevels();
  601. map->name = VLC->generaltexth->allTexts[740];
  602. map->description = getMapDescription();
  603. map->difficulty = 1;
  604. addPlayerInfo();
  605. }
  606. void CMapGenerator::checkIsOnMap(const int3& tile) const
  607. {
  608. if (!map->isInTheMap(tile))
  609. throw rmgException(boost::to_string(boost::format("Tile %s is outside the map") % tile.toString()));
  610. }
  611. std::map<TRmgTemplateZoneId, CRmgTemplateZone*> CMapGenerator::getZones() const
  612. {
  613. return zones;
  614. }
  615. bool CMapGenerator::isBlocked(const int3 &tile) const
  616. {
  617. checkIsOnMap(tile);
  618. return tiles[tile.x][tile.y][tile.z].isBlocked();
  619. }
  620. bool CMapGenerator::shouldBeBlocked(const int3 &tile) const
  621. {
  622. checkIsOnMap(tile);
  623. return tiles[tile.x][tile.y][tile.z].shouldBeBlocked();
  624. }
  625. bool CMapGenerator::isPossible(const int3 &tile) const
  626. {
  627. checkIsOnMap(tile);
  628. return tiles[tile.x][tile.y][tile.z].isPossible();
  629. }
  630. bool CMapGenerator::isFree(const int3 &tile) const
  631. {
  632. checkIsOnMap(tile);
  633. return tiles[tile.x][tile.y][tile.z].isFree();
  634. }
  635. bool CMapGenerator::isUsed(const int3 &tile) const
  636. {
  637. checkIsOnMap(tile);
  638. return tiles[tile.x][tile.y][tile.z].isUsed();
  639. }
  640. bool CMapGenerator::isRoad(const int3& tile) const
  641. {
  642. checkIsOnMap(tile);
  643. return tiles[tile.x][tile.y][tile.z].isRoad();
  644. }
  645. void CMapGenerator::setOccupied(const int3 &tile, ETileType::ETileType state)
  646. {
  647. checkIsOnMap(tile);
  648. tiles[tile.x][tile.y][tile.z].setOccupied(state);
  649. }
  650. void CMapGenerator::setRoad(const int3& tile, ERoadType::ERoadType roadType)
  651. {
  652. checkIsOnMap(tile);
  653. tiles[tile.x][tile.y][tile.z].setRoadType(roadType);
  654. }
  655. CTileInfo CMapGenerator::getTile(const int3& tile) const
  656. {
  657. checkIsOnMap(tile);
  658. return tiles[tile.x][tile.y][tile.z];
  659. }
  660. TRmgTemplateZoneId CMapGenerator::getZoneID(const int3& tile) const
  661. {
  662. checkIsOnMap(tile);
  663. return zoneColouring[tile.z][tile.x][tile.y];
  664. }
  665. void CMapGenerator::setZoneID(const int3& tile, TRmgTemplateZoneId zid)
  666. {
  667. checkIsOnMap(tile);
  668. zoneColouring[tile.z][tile.x][tile.y] = zid;
  669. }
  670. bool CMapGenerator::isAllowedSpell(SpellID sid) const
  671. {
  672. assert(sid >= 0);
  673. if (sid < map->allowedSpell.size())
  674. {
  675. return map->allowedSpell[sid];
  676. }
  677. else
  678. return false;
  679. }
  680. void CMapGenerator::setNearestObjectDistance(int3 &tile, float value)
  681. {
  682. checkIsOnMap(tile);
  683. tiles[tile.x][tile.y][tile.z].setNearestObjectDistance(value);
  684. }
  685. float CMapGenerator::getNearestObjectDistance(const int3 &tile) const
  686. {
  687. checkIsOnMap(tile);
  688. return tiles[tile.x][tile.y][tile.z].getNearestObjectDistance();
  689. }
  690. int CMapGenerator::getNextMonlithIndex()
  691. {
  692. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  693. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  694. else
  695. return monolithIndex++;
  696. }
  697. int CMapGenerator::getPrisonsRemaning() const
  698. {
  699. return prisonsRemaining;
  700. }
  701. void CMapGenerator::decreasePrisonsRemaining()
  702. {
  703. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  704. }
  705. std::vector<ArtifactID> CMapGenerator::getQuestArtsRemaning() const
  706. {
  707. return questArtifacts;
  708. }
  709. void CMapGenerator::banQuestArt(ArtifactID id)
  710. {
  711. map->allowedArtifact[id] = false;
  712. vstd::erase_if_present (questArtifacts, id);
  713. }
  714. void CMapGenerator::registerZone (TFaction faction)
  715. {
  716. zonesPerFaction[faction]++;
  717. zonesTotal++;
  718. }
  719. ui32 CMapGenerator::getZoneCount(TFaction faction)
  720. {
  721. return zonesPerFaction[faction];
  722. }
  723. ui32 CMapGenerator::getTotalZoneCount() const
  724. {
  725. return zonesTotal;
  726. }