CMapGenerator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. //override config with game options
  74. if(!mapGenOptions.isRoadEnabled(config.secondaryRoadType))
  75. config.secondaryRoadType = "";
  76. if(!mapGenOptions.isRoadEnabled(config.defaultRoadType))
  77. config.defaultRoadType = config.secondaryRoadType;
  78. }
  79. const CMapGenerator::Config & CMapGenerator::getConfig() const
  80. {
  81. return config;
  82. }
  83. //must be instantiated in .cpp file for access to complete types of all member fields
  84. CMapGenerator::~CMapGenerator() = default;
  85. const CMapGenOptions& CMapGenerator::getMapGenOptions() const
  86. {
  87. return mapGenOptions;
  88. }
  89. void CMapGenerator::initPrisonsRemaining()
  90. {
  91. prisonsRemaining = 0;
  92. for (auto isAllowed : map->map().allowedHeroes)
  93. {
  94. if (isAllowed)
  95. prisonsRemaining++;
  96. }
  97. prisonsRemaining = std::max<int> (0, prisonsRemaining - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player
  98. }
  99. void CMapGenerator::initQuestArtsRemaining()
  100. {
  101. for (auto art : VLC->arth->objects)
  102. {
  103. if (art->aClass == CArtifact::ART_TREASURE && VLC->arth->legalArtifact(art->getId()) && art->constituentOf.empty()) //don't use parts of combined artifacts
  104. questArtifacts.push_back(art->getId());
  105. }
  106. }
  107. std::unique_ptr<CMap> CMapGenerator::generate()
  108. {
  109. Load::Progress::reset();
  110. Load::Progress::setupStepsTill(5, 30);
  111. try
  112. {
  113. addHeaderInfo();
  114. map->initTiles(*this);
  115. Load::Progress::step();
  116. initPrisonsRemaining();
  117. initQuestArtsRemaining();
  118. genZones();
  119. Load::Progress::step();
  120. map->map().calculateGuardingGreaturePositions(); //clear map so that all tiles are unguarded
  121. map->addModificators();
  122. Load::Progress::step(3);
  123. fillZones();
  124. //updated guarded tiles will be calculated in CGameState::initMapObjects()
  125. map->getZones().clear();
  126. }
  127. catch (rmgException &e)
  128. {
  129. logGlobal->error("Random map generation received exception: %s", e.what());
  130. }
  131. Load::Progress::finish();
  132. return std::move(map->mapInstance);
  133. }
  134. std::string CMapGenerator::getMapDescription() const
  135. {
  136. assert(map);
  137. const std::string waterContentStr[3] = { "none", "normal", "islands" };
  138. const std::string monsterStrengthStr[3] = { "weak", "normal", "strong" };
  139. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EGlobalMonsterStrength::WEAK; //does not start from 0
  140. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  141. if(!mapTemplate)
  142. throw rmgException("Map template for Random Map Generator is not found. Could not start the game.");
  143. std::stringstream ss;
  144. ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, Random seed was %d, size %dx%d") +
  145. ", levels %d, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
  146. randomSeed % map->map().width % map->map().height % static_cast<int>(map->map().levels()) % static_cast<int>(mapGenOptions.getPlayerCount()) %
  147. static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
  148. monsterStrengthStr[monsterStrengthIndex]);
  149. for(const auto & pair : mapGenOptions.getPlayersSettings())
  150. {
  151. const auto & pSettings = pair.second;
  152. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  153. {
  154. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()] << " is human";
  155. }
  156. if(pSettings.getStartingTown() != CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  157. {
  158. ss << ", " << GameConstants::PLAYER_COLOR_NAMES[pSettings.getColor().getNum()]
  159. << " town choice is " << (*VLC->townh)[pSettings.getStartingTown()]->getNameTranslated();
  160. }
  161. }
  162. return ss.str();
  163. }
  164. void CMapGenerator::addPlayerInfo()
  165. {
  166. // Calculate which team numbers exist
  167. enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2}; // Used as a kind of a local named array index, so left as enum, not enum class
  168. std::array<std::list<int>, 2> teamNumbers;
  169. std::set<int> teamsTotal;
  170. int teamOffset = 0;
  171. int playerCount = 0;
  172. int teamCount = 0;
  173. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  174. {
  175. if (i == CPHUMAN)
  176. {
  177. playerCount = mapGenOptions.getPlayerCount();
  178. teamCount = mapGenOptions.getTeamCount();
  179. }
  180. else
  181. {
  182. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  183. teamCount = mapGenOptions.getCompOnlyTeamCount();
  184. }
  185. if(playerCount == 0)
  186. {
  187. continue;
  188. }
  189. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  190. int teamCountNorm = teamCount;
  191. if(teamCountNorm == 0)
  192. {
  193. teamCountNorm = playerCount;
  194. }
  195. for(int j = 0; j < teamCountNorm; ++j)
  196. {
  197. for(int k = 0; k < playersPerTeam; ++k)
  198. {
  199. teamNumbers[i].push_back(j + teamOffset);
  200. }
  201. }
  202. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  203. {
  204. teamNumbers[i].push_back(j + teamOffset);
  205. }
  206. teamOffset += teamCountNorm;
  207. }
  208. // Team numbers are assigned randomly to every player
  209. //TODO: allow customize teams in rmg template
  210. for(const auto & pair : mapGenOptions.getPlayersSettings())
  211. {
  212. const auto & pSettings = pair.second;
  213. PlayerInfo player;
  214. player.canComputerPlay = true;
  215. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  216. if (j == CPHUMAN)
  217. {
  218. player.canHumanPlay = true;
  219. }
  220. if(pSettings.getTeam() != TeamID::NO_TEAM)
  221. {
  222. player.team = pSettings.getTeam();
  223. }
  224. else
  225. {
  226. if (teamNumbers[j].empty())
  227. {
  228. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  229. assert (teamNumbers[j].size());
  230. }
  231. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
  232. player.team = TeamID(*itTeam);
  233. teamNumbers[j].erase(itTeam);
  234. }
  235. teamsTotal.insert(player.team.getNum());
  236. map->map().players[pSettings.getColor().getNum()] = player;
  237. }
  238. map->map().howManyTeams = teamsTotal.size();
  239. }
  240. void CMapGenerator::genZones()
  241. {
  242. CZonePlacer placer(*map);
  243. placer.placeZones(&rand);
  244. placer.assignZones(&rand);
  245. logGlobal->info("Zones generated successfully");
  246. }
  247. void CMapGenerator::createWaterTreasures()
  248. {
  249. if (!getZoneWater())
  250. return;
  251. //add treasures on water
  252. for (const auto& treasureInfo : getConfig().waterTreasure)
  253. {
  254. getZoneWater()->addTreasureInfo(treasureInfo);
  255. }
  256. }
  257. void CMapGenerator::fillZones()
  258. {
  259. findZonesForQuestArts();
  260. createWaterTreasures();
  261. logGlobal->info("Started filling zones");
  262. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  263. //place main town in the middle
  264. Load::Progress::setupStepsTill(map->getZones().size(), 50);
  265. for (const auto& it : map->getZones())
  266. {
  267. it.second->initFreeTiles();
  268. it.second->initModificators();
  269. Progress::Progress::step();
  270. }
  271. Load::Progress::setupStepsTill(map->getZones().size(), 240);
  272. std::vector<std::shared_ptr<Zone>> treasureZones;
  273. for (const auto& it : map->getZones())
  274. {
  275. it.second->processModificators();
  276. if (it.second->getType() == ETemplateZoneType::TREASURE)
  277. treasureZones.push_back(it.second);
  278. Progress::Progress::step();
  279. }
  280. //find place for Grail
  281. if (treasureZones.empty())
  282. {
  283. for (const auto& it : map->getZones())
  284. if (it.second->getType() != ETemplateZoneType::WATER)
  285. treasureZones.push_back(it.second);
  286. }
  287. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, rand);
  288. map->map().grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths().getTiles(), rand);
  289. logGlobal->info("Zones filled successfully");
  290. Load::Progress::set(250);
  291. }
  292. void CMapGenerator::findZonesForQuestArts()
  293. {
  294. //we want to place arties in zones that were not yet filled (higher index)
  295. for (auto connection : mapGenOptions.getMapTemplate()->getConnections())
  296. {
  297. auto zoneA = map->getZones()[connection.getZoneA()];
  298. auto zoneB = map->getZones()[connection.getZoneB()];
  299. if (zoneA->getId() > zoneB->getId())
  300. {
  301. if(auto * m = zoneB->getModificator<TreasurePlacer>())
  302. m->setQuestArtZone(zoneA.get());
  303. }
  304. else if (zoneA->getId() < zoneB->getId())
  305. {
  306. if(auto * m = zoneA->getModificator<TreasurePlacer>())
  307. m->setQuestArtZone(zoneB.get());
  308. }
  309. }
  310. }
  311. void CMapGenerator::addHeaderInfo()
  312. {
  313. map->map().version = EMapFormat::VCMI;
  314. map->map().width = mapGenOptions.getWidth();
  315. map->map().height = mapGenOptions.getHeight();
  316. map->map().twoLevel = mapGenOptions.getHasTwoLevels();
  317. map->map().name = VLC->generaltexth->allTexts[740];
  318. map->map().description = getMapDescription();
  319. map->map().difficulty = 1;
  320. addPlayerInfo();
  321. }
  322. int CMapGenerator::getNextMonlithIndex()
  323. {
  324. while (true)
  325. {
  326. if (monolithIndex >= VLC->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  327. throw rmgException(boost::to_string(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  328. else
  329. {
  330. //Skip modded Monoliths which can't beplaced on every terrain
  331. auto templates = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, monolithIndex)->getTemplates();
  332. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  333. {
  334. monolithIndex++;
  335. }
  336. else
  337. {
  338. return monolithIndex++;
  339. }
  340. }
  341. }
  342. }
  343. int CMapGenerator::getPrisonsRemaning() const
  344. {
  345. return prisonsRemaining;
  346. }
  347. void CMapGenerator::decreasePrisonsRemaining()
  348. {
  349. prisonsRemaining = std::max (0, prisonsRemaining - 1);
  350. }
  351. const std::vector<ArtifactID> & CMapGenerator::getQuestArtsRemaning() const
  352. {
  353. return questArtifacts;
  354. }
  355. void CMapGenerator::banQuestArt(const ArtifactID & id)
  356. {
  357. map->map().allowedArtifact[id] = false;
  358. vstd::erase_if_present(questArtifacts, id);
  359. }
  360. Zone * CMapGenerator::getZoneWater() const
  361. {
  362. for(auto & z : map->getZones())
  363. if(z.second->getType() == ETemplateZoneType::WATER)
  364. return z.second.get();
  365. return nullptr;
  366. }
  367. VCMI_LIB_NAMESPACE_END