CMapGenerator.cpp 15 KB

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