CMapGenerator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 "../GameLibrary.h"
  15. #include "../texts/CGeneralTextHandler.h"
  16. #include "../CRandomGenerator.h"
  17. #include "../entities/artifact/CArtHandler.h"
  18. #include "../entities/faction/CTownHandler.h"
  19. #include "../entities/faction/CFaction.h"
  20. #include "../entities/hero/CHero.h"
  21. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  22. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  23. #include "../mapping/CMapEditManager.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 "modificators/ObjectManager.h"
  32. #include "modificators/TreasurePlacer.h"
  33. #include "modificators/RoadPlacer.h"
  34. #include <vstd/RNG.h>
  35. #include <vcmi/HeroTypeService.h>
  36. #include <tbb/task_group.h>
  37. VCMI_LIB_NAMESPACE_BEGIN
  38. CMapGenerator::CMapGenerator(CMapGenOptions& mapGenOptions, IGameInfoCallback * 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 : LIBRARY->arth->getDefaultAllowed())
  98. {
  99. auto art = artID.toArtifact();
  100. //Don't use parts of combined artifacts
  101. if (art->aClass == EArtifactClass::ART_TREASURE && LIBRARY->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. MetaString CMapGenerator::getMapDescription() const
  140. {
  141. const TextIdentifier mainPattern("vcmi", "randomMap", "description");
  142. const TextIdentifier isHuman("vcmi", "randomMap", "description", "isHuman");
  143. const TextIdentifier townChoiceIs("vcmi", "randomMap", "description", "townChoice");
  144. const std::array waterContent = {
  145. TextIdentifier("vcmi", "randomMap", "description", "water", "none"),
  146. TextIdentifier("vcmi", "randomMap", "description", "water", "normal"),
  147. TextIdentifier("vcmi", "randomMap", "description", "water", "islands")
  148. };
  149. const std::array monsterStrength = {
  150. TextIdentifier("vcmi", "randomMap", "description", "monster", "weak"),
  151. TextIdentifier("vcmi", "randomMap", "description", "monster", "normal"),
  152. TextIdentifier("vcmi", "randomMap", "description", "monster", "strong")
  153. };
  154. const auto * mapTemplate = mapGenOptions.getMapTemplate();
  155. int monsterStrengthIndex = mapGenOptions.getMonsterStrength() - EMonsterStrength::GLOBAL_WEAK; //does not start from 0
  156. MetaString result = MetaString::createFromTextID(mainPattern.get());
  157. result.replaceRawString(mapTemplate->getName());
  158. result.replaceNumber(map->width());
  159. result.replaceNumber(map->height());
  160. result.replaceNumber(map->levels());
  161. result.replaceNumber(mapGenOptions.getHumanOrCpuPlayerCount());
  162. result.replaceNumber(mapGenOptions.getCompOnlyPlayerCount());
  163. result.replaceTextID(waterContent.at(mapGenOptions.getWaterContent()).get());
  164. result.replaceTextID(monsterStrength.at(monsterStrengthIndex).get());
  165. for(const auto & pair : mapGenOptions.getPlayersSettings())
  166. {
  167. const auto & pSettings = pair.second;
  168. if(pSettings.getPlayerType() == EPlayerType::HUMAN)
  169. {
  170. result.appendTextID(isHuman.get());
  171. result.replaceName(pSettings.getColor());
  172. }
  173. if(pSettings.getStartingTown() != FactionID::RANDOM)
  174. {
  175. result.appendTextID(townChoiceIs.get());
  176. result.replaceName(pSettings.getColor());
  177. result.replaceName(pSettings.getStartingTown());
  178. }
  179. }
  180. return result;
  181. }
  182. void CMapGenerator::addPlayerInfo()
  183. {
  184. // Teams are already configured in CMapGenOptions. However, it's not the case when it comes to map editor
  185. std::set<TeamID> teamsTotal;
  186. if (mapGenOptions.arePlayersCustomized())
  187. {
  188. // Simply copy existing settings set in GUI
  189. for (const auto & player : mapGenOptions.getPlayersSettings())
  190. {
  191. PlayerInfo playerInfo;
  192. playerInfo.team = player.second.getTeam();
  193. if (player.second.getPlayerType() == EPlayerType::COMP_ONLY)
  194. {
  195. playerInfo.canHumanPlay = false;
  196. }
  197. else
  198. {
  199. playerInfo.canHumanPlay = true;
  200. }
  201. map->getMap(this).players[player.first.getNum()] = playerInfo;
  202. teamsTotal.insert(player.second.getTeam());
  203. }
  204. }
  205. else
  206. {
  207. // Assign standard teams (in map editor)
  208. // Calculate which team numbers exist
  209. 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
  210. std::array<std::list<int>, 2> teamNumbers;
  211. int teamOffset = 0;
  212. int playerCount = 0;
  213. int teamCount = 0;
  214. // FIXME: Player can be any color, not just 0
  215. for (int i = CPHUMAN; i < AFTER_LAST; ++i)
  216. {
  217. if (i == CPHUMAN)
  218. {
  219. playerCount = mapGenOptions.getHumanOrCpuPlayerCount();
  220. teamCount = mapGenOptions.getTeamCount();
  221. }
  222. else
  223. {
  224. playerCount = mapGenOptions.getCompOnlyPlayerCount();
  225. teamCount = mapGenOptions.getCompOnlyTeamCount();
  226. }
  227. if(playerCount == 0)
  228. {
  229. continue;
  230. }
  231. int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
  232. int teamCountNorm = teamCount;
  233. if(teamCountNorm == 0)
  234. {
  235. teamCountNorm = playerCount;
  236. }
  237. for(int j = 0; j < teamCountNorm; ++j)
  238. {
  239. for(int k = 0; k < playersPerTeam; ++k)
  240. {
  241. teamNumbers[i].push_back(j + teamOffset);
  242. }
  243. }
  244. for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
  245. {
  246. teamNumbers[i].push_back(j + teamOffset);
  247. }
  248. teamOffset += teamCountNorm;
  249. }
  250. logGlobal->info("Current player settings size: %d", mapGenOptions.getPlayersSettings().size());
  251. // Team numbers are assigned randomly to every player
  252. //TODO: allow to customize teams in rmg template
  253. for(const auto & pair : mapGenOptions.getPlayersSettings())
  254. {
  255. const auto & pSettings = pair.second;
  256. PlayerInfo player;
  257. player.canComputerPlay = true;
  258. int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
  259. if (j == CPHUMAN)
  260. {
  261. player.canHumanPlay = true;
  262. }
  263. if(pSettings.getTeam() != TeamID::NO_TEAM)
  264. {
  265. player.team = pSettings.getTeam();
  266. }
  267. else
  268. {
  269. if (teamNumbers[j].empty())
  270. {
  271. logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
  272. assert (teamNumbers[j].size());
  273. }
  274. auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], *rand);
  275. player.team = TeamID(*itTeam);
  276. teamNumbers[j].erase(itTeam);
  277. }
  278. teamsTotal.insert(player.team);
  279. map->getMap(this).players[pSettings.getColor().getNum()] = player;
  280. }
  281. logGlobal->info("Current team count: %d", teamsTotal.size());
  282. }
  283. // FIXME: 0
  284. // Can't find info for player 0 (starting zone)
  285. // Can't find info for player 1 (starting zone)
  286. map->getMap(this).howManyTeams = teamsTotal.size();
  287. }
  288. void CMapGenerator::genZones()
  289. {
  290. placer->placeZones(rand.get());
  291. placer->assignZones(rand.get());
  292. logGlobal->info("Zones generated successfully");
  293. }
  294. void CMapGenerator::addWaterTreasuresInfo()
  295. {
  296. if (!getZoneWater())
  297. return;
  298. //add treasures on water
  299. for (const auto& treasureInfo : getConfig().waterTreasure)
  300. {
  301. getZoneWater()->addTreasureInfo(treasureInfo);
  302. }
  303. }
  304. void CMapGenerator::fillZones()
  305. {
  306. addWaterTreasuresInfo();
  307. logGlobal->info("Started filling zones");
  308. size_t numZones = map->getZones().size();
  309. //we need info about all town types to evaluate dwellings and pandoras with creatures properly
  310. //place main town in the middle
  311. Load::Progress::setupStepsTill(numZones, 50);
  312. for (const auto& it : map->getZones())
  313. {
  314. it.second->initFreeTiles();
  315. it.second->initModificators();
  316. Progress::Progress::step();
  317. }
  318. std::vector<std::shared_ptr<Zone>> treasureZones;
  319. TModificators allJobs;
  320. for (auto& it : map->getZones())
  321. {
  322. allJobs.splice(allJobs.end(), it.second->getModificators());
  323. }
  324. Load::Progress::setupStepsTill(allJobs.size(), 240);
  325. if (config.singleThread) //No thread pool, just queue with deterministic order
  326. {
  327. while (!allJobs.empty())
  328. {
  329. for (auto it = allJobs.begin(); it != allJobs.end();)
  330. {
  331. if ((*it)->isReady())
  332. {
  333. auto jobCopy = *it;
  334. jobCopy->run();
  335. Progress::Progress::step(); //Update progress bar
  336. allJobs.erase(it);
  337. break; //Restart from the first job
  338. }
  339. else
  340. {
  341. ++it;
  342. }
  343. }
  344. }
  345. }
  346. else
  347. {
  348. tbb::task_group pool;
  349. while (!allJobs.empty())
  350. {
  351. for (auto it = allJobs.begin(); it != allJobs.end();)
  352. {
  353. if ((*it)->isFinished())
  354. {
  355. it = allJobs.erase(it);
  356. Progress::Progress::step();
  357. }
  358. else if ((*it)->isReady())
  359. {
  360. auto jobCopy = *it;
  361. pool.run([this, jobCopy]() -> void
  362. {
  363. jobCopy->run();
  364. Progress::Progress::step(); //Update progress bar
  365. }
  366. );
  367. it = allJobs.erase(it);
  368. }
  369. else
  370. {
  371. ++it;
  372. }
  373. }
  374. }
  375. //Wait for all the tasks
  376. pool.wait();
  377. }
  378. for (const auto& it : map->getZones())
  379. {
  380. if (it.second->getType() == ETemplateZoneType::TREASURE)
  381. treasureZones.push_back(it.second);
  382. }
  383. //find place for Grail
  384. if (treasureZones.empty())
  385. {
  386. for (const auto& it : map->getZones())
  387. if (it.second->getType() != ETemplateZoneType::WATER)
  388. treasureZones.push_back(it.second);
  389. }
  390. auto grailZone = *RandomGeneratorUtil::nextItem(treasureZones, *rand);
  391. map->getMap(this).grailPos = *RandomGeneratorUtil::nextItem(grailZone->freePaths()->getTiles(), *rand);
  392. map->getMap(this).reindexObjects();
  393. logGlobal->info("Zones filled successfully");
  394. Load::Progress::set(250);
  395. }
  396. void CMapGenerator::addHeaderInfo()
  397. {
  398. auto& m = map->getMap(this);
  399. m.version = EMapFormat::VCMI;
  400. m.width = mapGenOptions.getWidth();
  401. m.height = mapGenOptions.getHeight();
  402. m.twoLevel = mapGenOptions.getHasTwoLevels();
  403. m.name.appendLocalString(EMetaText::GENERAL_TXT, 740);
  404. m.description = getMapDescription();
  405. m.difficulty = EMapDifficulty::NORMAL;
  406. addPlayerInfo();
  407. m.waterMap = (mapGenOptions.getWaterContent() != EWaterContent::EWaterContent::NONE);
  408. m.banWaterContent();
  409. m.overrideGameSettings(mapGenOptions.getMapTemplate()->getMapSettings());
  410. }
  411. int CMapGenerator::getNextMonlithIndex()
  412. {
  413. while (true)
  414. {
  415. if (monolithIndex >= LIBRARY->objtypeh->knownSubObjects(Obj::MONOLITH_TWO_WAY).size())
  416. throw rmgException(boost::str(boost::format("There is no Monolith Two Way with index %d available!") % monolithIndex));
  417. else
  418. {
  419. //Skip modded Monoliths which can't beplaced on every terrain
  420. auto templates = LIBRARY->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, monolithIndex)->getTemplates();
  421. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  422. {
  423. monolithIndex++;
  424. }
  425. else
  426. {
  427. return monolithIndex++;
  428. }
  429. }
  430. }
  431. }
  432. std::shared_ptr<CZonePlacer> CMapGenerator::getZonePlacer() const
  433. {
  434. return placer;
  435. }
  436. const std::vector<ArtifactID> & CMapGenerator::getAllPossibleQuestArtifacts() const
  437. {
  438. return questArtifacts;
  439. }
  440. const std::vector<HeroTypeID> CMapGenerator::getAllPossibleHeroes() const
  441. {
  442. auto isWaterMap = map->getMap(this).isWaterMap();
  443. //Skip heroes that were banned, including the ones placed in prisons
  444. std::vector<HeroTypeID> ret;
  445. for (HeroTypeID hero : map->getMap(this).allowedHeroes)
  446. {
  447. auto * h = dynamic_cast<const CHero*>(LIBRARY->heroTypes()->getById(hero));
  448. if(h->onlyOnWaterMap && !isWaterMap)
  449. continue;
  450. if(h->onlyOnMapWithoutWater && isWaterMap)
  451. continue;
  452. bool heroUsedAsStarting = false;
  453. for (auto const & player : map->getMapGenOptions().getPlayersSettings())
  454. {
  455. if (player.second.getStartingHero() == hero)
  456. {
  457. heroUsedAsStarting = true;
  458. break;
  459. }
  460. }
  461. if (heroUsedAsStarting)
  462. continue;
  463. ret.push_back(hero);
  464. }
  465. return ret;
  466. }
  467. void CMapGenerator::banQuestArt(const ArtifactID & id)
  468. {
  469. map->getMap(this).allowedArtifact.erase(id);
  470. }
  471. void CMapGenerator::unbanQuestArt(const ArtifactID & id)
  472. {
  473. map->getMap(this).allowedArtifact.insert(id);
  474. }
  475. Zone * CMapGenerator::getZoneWater() const
  476. {
  477. for(auto & z : map->getZones())
  478. if(z.second->getType() == ETemplateZoneType::WATER)
  479. return z.second.get();
  480. return nullptr;
  481. }
  482. VCMI_LIB_NAMESPACE_END