CMapGenerator.cpp 12 KB

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