CMapGenerator.cpp 14 KB

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