CMapGenerator.cpp 15 KB

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