CMapGenerator.cpp 22 KB

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