CMapGenerator.cpp 12 KB

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