CMapGenerator.cpp 12 KB

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