CMapGenerator.cpp 15 KB

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