CMapGenerator.cpp 15 KB

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