CMapGenerator.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. #include "TileInfo.h"
  22. #include "Zone.h"
  23. #include "Functions.h"
  24. #include "RmgMap.h"
  25. #include "ObjectManager.h"
  26. #include "TreasurePlacer.h"
  27. #include "RoadPlacer.h"
  28. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, int RandomSeed) :
  29. mapGenOptions(mapGenOptions), randomSeed(RandomSeed),
  30. prisonsRemaining(0), monolithIndex(0)
  31. {
  32. loadConfig();
  33. rand.setSeed(this->randomSeed);
  34. mapGenOptions.finalize(rand);
  35. map = std::make_unique<RmgMap>(mapGenOptions);
  36. }
  37. int CMapGenerator::getRandomSeed() const
  38. {
  39. return randomSeed;
  40. }
  41. void CMapGenerator::loadConfig()
  42. {
  43. static const ResourceID path("config/randomMap.json");
  44. JsonNode randomMapJson(path);
  45. for(auto& s : randomMapJson["terrain"]["undergroundAllow"].Vector())
  46. {
  47. if(!s.isNull())
  48. config.terrainUndergroundAllowed.emplace_back(s.String());
  49. }
  50. for(auto& s : randomMapJson["terrain"]["groundProhibit"].Vector())
  51. {
  52. if(!s.isNull())
  53. config.terrainGroundProhibit.emplace_back(s.String());
  54. }
  55. config.shipyardGuard = randomMapJson["waterZone"]["shipyard"]["value"].Integer();
  56. for(auto & treasure : randomMapJson["waterZone"]["treasure"].Vector())
  57. {
  58. config.waterTreasure.emplace_back(treasure["min"].Integer(), treasure["max"].Integer(), treasure["density"].Integer());
  59. }
  60. config.mineExtraResources = randomMapJson["mines"]["extraResourcesLimit"].Integer();
  61. config.minGuardStrength = randomMapJson["minGuardStrength"].Integer();
  62. config.defaultRoadType = randomMapJson["defaultRoadType"].String();
  63. config.treasureValueLimit = randomMapJson["treasureValueLimit"].Integer();
  64. for(auto & i : randomMapJson["prisons"]["experience"].Vector())
  65. config.prisonExperience.push_back(i.Integer());
  66. for(auto & i : randomMapJson["prisons"]["value"].Vector())
  67. config.prisonValues.push_back(i.Integer());
  68. for(auto & i : randomMapJson["scrolls"]["value"].Vector())
  69. config.scrollValues.push_back(i.Integer());
  70. for(auto & i : randomMapJson["pandoras"]["creaturesValue"].Vector())
  71. config.pandoraCreatureValues.push_back(i.Integer());
  72. for(auto & i : randomMapJson["quests"]["value"].Vector())
  73. config.questValues.push_back(i.Integer());
  74. for(auto & i : randomMapJson["quests"]["rewardValue"].Vector())
  75. config.questRewardValues.push_back(i.Integer());
  76. config.pandoraMultiplierGold = randomMapJson["pandoras"]["valueMultiplierGold"].Integer();
  77. config.pandoraMultiplierExperience = randomMapJson["pandoras"]["valueMultiplierExperience"].Integer();
  78. config.pandoraMultiplierSpells = randomMapJson["pandoras"]["valueMultiplierSpells"].Integer();
  79. config.pandoraSpellSchool = randomMapJson["pandoras"]["valueSpellSchool"].Integer();
  80. config.pandoraSpell60 = randomMapJson["pandoras"]["valueSpell60"].Integer();
  81. }
  82. const CMapGenerator::Config & CMapGenerator::getConfig() const
  83. {
  84. return config;
  85. }
  86. CMapGenerator::~CMapGenerator()
  87. {
  88. }
  89. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  90. {
  91. return mapGenOptions;
  92. }
  93. void CMapGenerator::initPrisonsRemaining()
  94. {
  95. prisonsRemaining = 0;
  96. for (auto isAllowed : map->map().allowedHeroes)
  97. {
  98. if (isAllowed)
  99. prisonsRemaining++;
  100. }
  101. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player
  102. }
  103. void CMapGenerator::initQuestArtsRemaining()
  104. {
  105. for (auto art : VLC->arth->objects)
  106. {
  107. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->id) && art->constituentOf.empty()) //don't use parts of combined artifacts
  108. questArtifacts.push_back(art->id);
  109. }
  110. }
  111. std::unique_ptr<CMap> CMapGenerator::generate()
  112. {
  113. try
  114. {
  115. addHeaderInfo();
  116. map->initTiles(*this);
  117. initPrisonsRemaining();
  118. initQuestArtsRemaining();
  119. genZones();
  120. map->map().calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  121. map->addModificators();
  122. fillZones();
  123. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  124. map->getZones().clear();
  125. }
  126. catch (rmgException &e)
  127. {
  128. logGlobal->error("Random map generation received exception: %s", e.what());
  129. }
  130. return std::move(map->mapInstance);
  131. }
  132. std::string CMapGenerator::getMapDescription() const
  133. {
  134. assert(map);
  135. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  136. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  137. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  138. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  139. if(!mapTemplate)
  140. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  141. std::stringstream ss;
  142. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  143. ", levels %s, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  144. randomSeed % map->map().width % map->map().height % (map->map().twoLevel ? "2" : "1") % static_cast<int>(mapGenOptions.getPlayerCount()) %
  145. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  146. monsterStrengthStr[monsterStrengthIndex]);
  147. for(const auto & pair : mapGenOptions.getPlayersSettings())
  148. {
  149. const auto & pSettings = pair.second;
  150. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  151. {
  152. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  153. }
  154. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  155. {
  156. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  157. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->name;
  158. }
  159. }
  160. return ss.str();
  161. }
  162. void CMapGenerator::addPlayerInfo()
  163. {
  164. // Calculate which team numbers exist
  165. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2};
  166. std::array<std::list<int>, 2> teamNumbers;
  167. int teamOffset = 0;
  168. int playerCount = 0;
  169. int teamCount = 0;
  170. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  171. {
  172. if (i == CPHUMAN)
  173. {
  174. playerCount = mapGenOptions.getPlayerCount();
  175. teamCount = mapGenOptions.getTeamCount();
  176. }
  177. else
  178. {
  179. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  180. teamCount = mapGenOptions.getCompOnlyTeamCount();
  181. }
  182. if(playerCount == 0)
  183. {
  184. continue;
  185. }
  186. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  187. int teamCountNorm = teamCount;
  188. if(teamCountNorm == 0)
  189. {
  190. teamCountNorm = playerCount;
  191. }
  192. for(int j = 0; j < teamCountNorm; ++j)
  193. {
  194. for(int k = 0; k < playersPerTeam; ++k)
  195. {
  196. teamNumbers[i].push_back(j + teamOffset);
  197. }
  198. }
  199. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  200. {
  201. teamNumbers[i].push_back(j + teamOffset);
  202. }
  203. teamOffset += teamCountNorm;
  204. }
  205. // Team numbers are assigned randomly to every player
  206. //TODO: allow customize teams in rmg template
  207. for(const auto & pair : mapGenOptions.getPlayersSettings())
  208. {
  209. const auto & pSettings = pair.second;
  210. PlayerInfo player;
  211. player.canComputerPlay = true;
  212. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  213. if (j == CPHUMAN)
  214. {
  215. player.canHumanPlay = true;
  216. }
  217. if (teamNumbers[j].empty())
  218. {
  219. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  220. assert (teamNumbers[j].size());
  221. }
  222. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  223. player.team = TeamID(*itTeam);
  224. teamNumbers[j].erase(itTeam);
  225. map->map().players[pSettings.getColor().getNum()] = player;
  226. }
  227. map->map().howManyTeams = (mapGenOptions.getTeamCount() == 0 ? mapGenOptions.getPlayerCount() : mapGenOptions.getTeamCount())
  228. + (mapGenOptions.getCompOnlyTeamCount() == 0 ? mapGenOptions.getCompOnlyPlayerCount() : mapGenOptions.getCompOnlyTeamCount());
  229. }
  230. void CMapGenerator::genZones()
  231. {
  232. CZonePlacer placer(*map);
  233. placer.placeZones(&rand);
  234. placer.assignZones(&rand);
  235. logGlobal->info("Zones generated successfully");
  236. }
  237. void CMapGenerator::createWaterTreasures()
  238. {
  239. if(!getZoneWater())
  240. return;
  241. //add treasures on water
  242. for(auto & treasureInfo : getConfig().waterTreasure)
  243. {
  244. getZoneWater()->addTreasureInfo(treasureInfo);
  245. }
  246. }
  247. void CMapGenerator::fillZones()
  248. {
  249. findZonesForQuestArts();
  250. createWaterTreasures();
  251. logGlobal->info("Started filling zones");
  252. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  253. //place main town in the middle
  254. for(auto it : map->getZones())
  255. {
  256. it.second->initModificators();
  257. it.second->initFreeTiles();
  258. }
  259. std::vector<std::shared_ptr<Zone>> treasureZones;
  260. for(auto it : map->getZones())
  261. {
  262. it.second->processModificators();
  263. if (it.second->getType() == ETemplateZoneType::TREASURE)
  264. treasureZones.push_back(it.second);
  265. }
  266. //find place for Grail
  267. if(treasureZones.empty())
  268. {
  269. for(auto it : map->getZones())
  270. if(it.second->getType() != ETemplateZoneType::WATER)
  271. treasureZones.push_back(it.second);
  272. }
  273. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  274. map->map().grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths().getTiles(), rand);
  275. logGlobal->info("Zones filled successfully");
  276. }
  277. void CMapGenerator::findZonesForQuestArts()
  278. {
  279. //we want to place arties in zones that were not yet filled (higher index)
  280. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  281. {
  282. auto zoneA = map->getZones()[connection.getZoneA()];
  283. auto zoneB = map->getZones()[connection.getZoneB()];
  284. if (zoneA->getId() > zoneB->getId())
  285. {
  286. if(auto * m = zoneB->getModificator<TreasurePlacer>())
  287. zoneB->getModificator<TreasurePlacer>()->setQuestArtZone(zoneA.get());
  288. }
  289. else if (zoneA->getId() < zoneB->getId())
  290. {
  291. if(auto * m = zoneA->getModificator<TreasurePlacer>())
  292. zoneA->getModificator<TreasurePlacer>()->setQuestArtZone(zoneB.get());
  293. }
  294. }
  295. }
  296. void CMapGenerator::addHeaderInfo()
  297. {
  298. map->map().version = EMapFormat::VCMI;
  299. map->map().width = mapGenOptions.getWidth();
  300. map->map().height = mapGenOptions.getHeight();
  301. map->map().twoLevel = mapGenOptions.getHasTwoLevels();
  302. map->map().name = VLC->generaltexth->allTexts[740];
  303. map->map().description = getMapDescription();
  304. map->map().difficulty = 1;
  305. addPlayerInfo();
  306. }
  307. int CMapGenerator::getNextMonlithIndex()
  308. {
  309. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  310. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  311. else
  312. return monolithIndex++;
  313. }
  314. int CMapGenerator::getPrisonsRemaning() const
  315. {
  316. return prisonsRemaining;
  317. }
  318. void CMapGenerator::decreasePrisonsRemaining()
  319. {
  320. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  321. }
  322. const std::vector<ArtifactID> & CMapGenerator::getQuestArtsRemaning() const
  323. {
  324. return questArtifacts;
  325. }
  326. void CMapGenerator::banQuestArt(ArtifactID id)
  327. {
  328. map->map().allowedArtifact[id] = false;
  329. vstd::erase_if_present(questArtifacts, id);
  330. }
  331. Zone * CMapGenerator::getZoneWater() const
  332. {
  333. for(auto & z : map->getZones())
  334. if(z.second->getType() == ETemplateZoneType::WATER)
  335. return z.second.get();
  336. return nullptr;
  337. }