CGameStateCampaign.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /*
  2. * CGameStateCampaign.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 "CGameStateCampaign.h"
  12. #include "CGameState.h"
  13. #include "QuestInfo.h"
  14. #include "../campaign/CampaignState.h"
  15. #include "../entities/artifact/ArtifactUtils.h"
  16. #include "../entities/artifact/CArtifact.h"
  17. #include "../entities/building/CBuilding.h"
  18. #include "../entities/building/CBuildingHandler.h"
  19. #include "../entities/hero/CHeroClass.h"
  20. #include "../entities/hero/CHero.h"
  21. #include "../mapping/CMapEditManager.h"
  22. #include "../mapObjects/CGHeroInstance.h"
  23. #include "../mapObjects/CGTownInstance.h"
  24. #include "../networkPacks/ArtifactLocation.h"
  25. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  26. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  27. #include "../StartInfo.h"
  28. #include "../mapping/CMap.h"
  29. #include "../CPlayerState.h"
  30. #include <vstd/RNG.h>
  31. #include <vcmi/HeroTypeService.h>
  32. VCMI_LIB_NAMESPACE_BEGIN
  33. CampaignHeroReplacement::CampaignHeroReplacement(std::shared_ptr<CGHeroInstance> hero, const ObjectInstanceID & heroPlaceholderId):
  34. hero(hero),
  35. heroPlaceholderId(heroPlaceholderId)
  36. {
  37. }
  38. CGameStateCampaign::CGameStateCampaign() = default;
  39. CGameStateCampaign::CGameStateCampaign(CGameState * owner):
  40. gameState(owner)
  41. {
  42. assert(gameState->scenarioOps->mode == EStartMode::CAMPAIGN);
  43. assert(gameState->scenarioOps->campState != nullptr);
  44. }
  45. void CGameStateCampaign::setGamestate(CGameState * owner)
  46. {
  47. gameState = owner;
  48. }
  49. std::optional<CampaignBonus> CGameStateCampaign::currentBonus() const
  50. {
  51. auto campaignState = gameState->scenarioOps->campState;
  52. return campaignState->getBonus(*campaignState->currentScenario());
  53. }
  54. std::optional<CampaignScenarioID> CGameStateCampaign::getHeroesSourceScenario() const
  55. {
  56. auto campaignState = gameState->scenarioOps->campState;
  57. auto bonus = currentBonus();
  58. if(bonus && bonus->type == CampaignBonusType::HEROES_FROM_PREVIOUS_SCENARIO)
  59. return static_cast<CampaignScenarioID>(bonus->info2);
  60. return campaignState->lastScenario();
  61. }
  62. void CGameStateCampaign::trimCrossoverHeroesParameters(vstd::RNG & randomGenerator, const CampaignTravel & travelOptions)
  63. {
  64. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  65. if(!travelOptions.whatHeroKeeps.experience)
  66. {
  67. //trimming experience
  68. for(auto & hero : campaignHeroReplacements)
  69. {
  70. hero.hero->initExp(randomGenerator);
  71. }
  72. }
  73. if(!travelOptions.whatHeroKeeps.primarySkills)
  74. {
  75. //trimming prim skills
  76. for(auto & hero : campaignHeroReplacements)
  77. {
  78. for(auto skill : PrimarySkill::ALL_SKILLS())
  79. {
  80. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  81. .And(Selector::subtype()(BonusSubtypeID(skill)))
  82. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  83. hero.hero->getLocalBonus(sel)->val = hero.hero->getHeroClass()->primarySkillInitial[skill.getNum()];
  84. }
  85. }
  86. }
  87. if(!travelOptions.whatHeroKeeps.secondarySkills)
  88. {
  89. //trimming sec skills
  90. for(auto & hero : campaignHeroReplacements)
  91. {
  92. hero.hero->secSkills = hero.hero->getHeroType()->secSkillsInit;
  93. hero.hero->recreateSecondarySkillsBonuses();
  94. }
  95. }
  96. if(!travelOptions.whatHeroKeeps.spells)
  97. {
  98. for(auto & hero : campaignHeroReplacements)
  99. {
  100. hero.hero->removeSpellbook();
  101. }
  102. }
  103. if(!travelOptions.whatHeroKeeps.artifacts)
  104. {
  105. //trimming artifacts
  106. for(auto & hero : campaignHeroReplacements)
  107. {
  108. const auto & checkAndRemoveArtifact = [&](const ArtifactPosition & artifactPosition) -> bool
  109. {
  110. if(artifactPosition == ArtifactPosition::SPELLBOOK)
  111. return false; // do not handle spellbook this way
  112. const ArtSlotInfo *info = hero.hero->getSlot(artifactPosition);
  113. if(!info)
  114. return false;
  115. // FIXME: double-check how H3 handles case of transferring components of a combined artifact if entire combined artifact is not transferrable
  116. // For example, what happens if hero has assembled Angelic Alliance, AA is not marked is transferrable, but Sandals can be transferred? Should artifact be disassembled?
  117. if (info->locked)
  118. return false;
  119. // TODO: why would there be nullptr artifacts?
  120. const CArtifactInstance *art = info->getArt();
  121. if(!art)
  122. return false;
  123. ArtifactLocation al(hero.hero->id, artifactPosition);
  124. bool takeable = travelOptions.artifactsKeptByHero.count(art->getTypeId());
  125. bool locked = hero.hero->getSlot(al.slot)->locked;
  126. if (!locked && takeable)
  127. {
  128. logGlobal->debug("Artifact %s from slot %d of hero %s will be transferred to next scenario", art->getType()->getJsonKey(), al.slot.getNum(), hero.hero->getHeroTypeName());
  129. hero.transferrableArtifacts.push_back(artifactPosition);
  130. }
  131. if (!locked && !takeable)
  132. {
  133. logGlobal->debug("Removing artifact %s from slot %d of hero %s", art->getType()->getJsonKey(), al.slot.getNum(), hero.hero->getHeroTypeName());
  134. gameState->map->removeArtifactInstance(*hero.hero, al.slot);
  135. return true;
  136. }
  137. return false;
  138. };
  139. // process on copy - removal of artifact will invalidate container
  140. auto artifactsWorn = hero.hero->artifactsWorn;
  141. for(const auto & art : artifactsWorn)
  142. checkAndRemoveArtifact(art.first);
  143. for (int slotNumber = 0; slotNumber < hero.hero->artifactsInBackpack.size();)
  144. {
  145. if (checkAndRemoveArtifact(ArtifactPosition::BACKPACK_START + slotNumber))
  146. continue; // artifact was removed and backpack slots were shifted -> test this slot again
  147. else
  148. slotNumber++; // artifact was kept for transfer -> test next slot
  149. };
  150. }
  151. }
  152. //trimming creatures
  153. for(auto & hero : campaignHeroReplacements)
  154. {
  155. auto shouldSlotBeErased = [&](CStackInstance & j) -> bool
  156. {
  157. CreatureID crid = j.getCreatureID();
  158. return !travelOptions.monstersKeptByHero.count(crid);
  159. };
  160. //generate list of slots without removing anything first to avoid iterator invalidation
  161. std::vector<SlotID> slotsToErase;
  162. for(auto &slotPair : hero.hero->Slots())
  163. if(shouldSlotBeErased(*slotPair.second))
  164. slotsToErase.push_back(slotPair.first);
  165. for (const auto slotID : slotsToErase)
  166. hero.hero->eraseStack(slotID);
  167. }
  168. // Removing short-term bonuses
  169. for(auto & hero : campaignHeroReplacements)
  170. {
  171. hero.hero->removeBonusesRecursive(CSelector(Bonus::OneDay)
  172. .Or(CSelector(Bonus::OneWeek))
  173. .Or(CSelector(Bonus::NTurns))
  174. .Or(CSelector(Bonus::NDays))
  175. .Or(CSelector(Bonus::OneBattle)));
  176. }
  177. }
  178. void CGameStateCampaign::placeCampaignHeroes(vstd::RNG & randomGenerator)
  179. {
  180. // place bonus hero
  181. auto campaignState = gameState->scenarioOps->campState;
  182. auto campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  183. bool campaignGiveHero = campaignBonus && campaignBonus->type == CampaignBonusType::HERO;
  184. if(campaignGiveHero)
  185. {
  186. auto playerColor = PlayerColor(campaignBonus->info1);
  187. auto it = gameState->scenarioOps->playerInfos.find(playerColor);
  188. if(it != gameState->scenarioOps->playerInfos.end())
  189. {
  190. HeroTypeID heroTypeId = HeroTypeID(campaignBonus->info2);
  191. if(heroTypeId == HeroTypeID::CAMP_RANDOM) // random bonus hero
  192. {
  193. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, playerColor);
  194. }
  195. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  196. }
  197. }
  198. logGlobal->debug("\tGenerate list of hero placeholders");
  199. generateCampaignHeroesToReplace();
  200. logGlobal->debug("\tPrepare crossover heroes");
  201. trimCrossoverHeroesParameters(randomGenerator, campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  202. // remove same heroes on the map which will be added through crossover heroes
  203. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  204. // with the same hero type id
  205. std::vector<std::shared_ptr<CGObjectInstance>> removedHeroes;
  206. std::set<HeroTypeID> reservedHeroes = campaignState->getReservedHeroes();
  207. std::set<HeroTypeID> heroesToRemove;
  208. for (auto const & heroID : reservedHeroes )
  209. {
  210. // Do not replace reserved heroes initially, e.g. in 1st campaign scenario in which they appear
  211. if (!campaignState->getHeroByType(heroID).isNull())
  212. heroesToRemove.insert(heroID);
  213. }
  214. for(auto & replacement : campaignHeroReplacements)
  215. if (replacement.heroPlaceholderId.hasValue())
  216. heroesToRemove.insert(replacement.hero->getHeroTypeID());
  217. for(auto & heroID : heroesToRemove)
  218. {
  219. auto * hero = gameState->getUsedHero(heroID);
  220. if(hero)
  221. {
  222. removedHeroes.push_back(gameState->map->eraseObject(hero->id));
  223. }
  224. }
  225. logGlobal->debug("\tReplace placeholders with heroes");
  226. replaceHeroesPlaceholders();
  227. // now add removed heroes again with unused type ID
  228. for(auto object : removedHeroes)
  229. {
  230. auto hero = dynamic_cast<CGHeroInstance*>(object.get());
  231. HeroTypeID heroTypeId;
  232. if(hero->ID == Obj::HERO)
  233. {
  234. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, hero->tempOwner);
  235. }
  236. else if(hero->ID == Obj::PRISON)
  237. {
  238. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  239. if(!unusedHeroTypeIds.empty())
  240. {
  241. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, randomGenerator));
  242. }
  243. else
  244. {
  245. logGlobal->error("No free hero type ID found to replace prison.");
  246. assert(0);
  247. }
  248. }
  249. else
  250. {
  251. assert(0); // should not happen
  252. }
  253. hero->setHeroType(heroTypeId);
  254. gameState->map->getEditManager()->insertObject(object);
  255. }
  256. }
  257. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  258. {
  259. auto curBonus = currentBonus();
  260. if(!curBonus)
  261. return;
  262. assert(curBonus->isBonusForHero());
  263. //apply bonus
  264. switch(curBonus->type)
  265. {
  266. case CampaignBonusType::SPELL:
  267. {
  268. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  269. break;
  270. }
  271. case CampaignBonusType::MONSTER:
  272. {
  273. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  274. {
  275. if(hero->slotEmpty(SlotID(i)))
  276. {
  277. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  278. break;
  279. }
  280. }
  281. break;
  282. }
  283. case CampaignBonusType::ARTIFACT:
  284. {
  285. if(!gameState->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  286. logGlobal->error("Cannot give starting artifact - no free slots!");
  287. break;
  288. }
  289. case CampaignBonusType::SPELL_SCROLL:
  290. {
  291. const auto scroll = gameState->createScroll(SpellID(curBonus->info2));
  292. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  293. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  294. gameState->map->putArtifactInstance(*hero, scroll->getId(), slot);
  295. else
  296. logGlobal->error("Cannot give starting scroll - no free slots!");
  297. break;
  298. }
  299. case CampaignBonusType::PRIMARY_SKILL:
  300. {
  301. const ui8 * ptr = reinterpret_cast<const ui8 *>(&curBonus->info2);
  302. for(auto skill : PrimarySkill::ALL_SKILLS())
  303. {
  304. int val = ptr[skill.getNum()];
  305. if(val == 0)
  306. continue;
  307. auto currentScenario = *gameState->scenarioOps->campState->currentScenario();
  308. auto bb = std::make_shared<Bonus>( BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, BonusSourceID(currentScenario), BonusSubtypeID(skill) );
  309. hero->addNewBonus(bb);
  310. }
  311. break;
  312. }
  313. case CampaignBonusType::SECONDARY_SKILL:
  314. {
  315. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  316. break;
  317. }
  318. }
  319. }
  320. void CGameStateCampaign::replaceHeroesPlaceholders()
  321. {
  322. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  323. {
  324. if (!campaignHeroReplacement.heroPlaceholderId.hasValue())
  325. continue;
  326. auto heroPlaceholder = gameState->map->getObject(campaignHeroReplacement.heroPlaceholderId);
  327. auto heroToPlace = campaignHeroReplacement.hero;
  328. if(heroPlaceholder->tempOwner.isValidPlayer())
  329. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  330. heroToPlace->setAnchorPos(heroPlaceholder->anchorPos());
  331. heroToPlace->setHeroType(heroToPlace->getHeroTypeID());
  332. heroToPlace->appearance = heroToPlace->getObjectHandler()->getTemplates().front();
  333. gameState->map->replaceObject(campaignHeroReplacement.heroPlaceholderId, heroToPlace);
  334. }
  335. }
  336. void CGameStateCampaign::transferMissingArtifacts(const CampaignTravel & travelOptions)
  337. {
  338. CGHeroInstance * receiver = nullptr;
  339. for(auto hero : gameState->map->getObjects<CGHeroInstance>())
  340. {
  341. if (!hero->getOwner().isValidPlayer())
  342. continue; // prisons
  343. if (gameState->getPlayerState(hero->getOwner())->isHuman())
  344. {
  345. receiver = hero;
  346. break;
  347. }
  348. }
  349. assert(receiver);
  350. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  351. {
  352. if (campaignHeroReplacement.heroPlaceholderId.hasValue())
  353. continue;
  354. auto donorHero = campaignHeroReplacement.hero;
  355. if (!donorHero)
  356. throw std::runtime_error("Failed to find hero to take artifacts from! Scenario: " + gameState->map->name.toString());
  357. // process in reverse - 2nd artifact from a backpack must be processed before 1st one to avoid invalidation of artifact positions
  358. for (auto const & artLocation : boost::adaptors::reverse(campaignHeroReplacement.transferrableArtifacts))
  359. {
  360. auto * artifact = donorHero->getArt(artLocation);
  361. logGlobal->debug("Removing artifact %s from slot %d of hero %s for transfer", artifact->getType()->getJsonKey(), artLocation.getNum(), donorHero->getHeroTypeName());
  362. gameState->map->removeArtifactInstance(*donorHero, artLocation);
  363. if (receiver)
  364. {
  365. logGlobal->debug("Granting artifact %s to hero %s for transfer", artifact->getType()->getJsonKey(), receiver->getHeroTypeName());
  366. const auto slot = ArtifactUtils::getArtAnyPosition(receiver, artifact->getTypeId());
  367. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  368. gameState->map->putArtifactInstance(*receiver, artifact->getId(), slot);
  369. else
  370. logGlobal->error("Cannot transfer artifact - no free slots!");
  371. }
  372. else
  373. logGlobal->error("Cannot transfer artifact - no receiver hero!");
  374. }
  375. }
  376. }
  377. void CGameStateCampaign::generateCampaignHeroesToReplace()
  378. {
  379. auto campaignState = gameState->scenarioOps->campState;
  380. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  381. std::vector<CGHeroPlaceholder *> placeholdersByType;
  382. campaignHeroReplacements.clear();
  383. // find all placeholders on map
  384. for(auto heroPlaceholder : gameState->map->getObjects<CGHeroPlaceholder>())
  385. {
  386. // only 1 field must be set
  387. assert(heroPlaceholder->powerRank.has_value() != heroPlaceholder->heroType.has_value());
  388. if(heroPlaceholder->powerRank)
  389. placeholdersByPower.push_back(heroPlaceholder);
  390. if(heroPlaceholder->heroType)
  391. placeholdersByType.push_back(heroPlaceholder);
  392. }
  393. //selecting heroes by type
  394. for(const auto * placeholder : placeholdersByType)
  395. {
  396. const auto & node = campaignState->getHeroByType(*placeholder->heroType);
  397. if (node.isNull())
  398. {
  399. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), LIBRARY->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  400. continue;
  401. }
  402. auto hero = campaignState->crossoverDeserialize(node, gameState->map.get());
  403. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  404. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  405. }
  406. auto lastScenario = getHeroesSourceScenario();
  407. if (lastScenario)
  408. {
  409. // sort hero placeholders descending power
  410. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  411. {
  412. return *a->powerRank > *b->powerRank;
  413. });
  414. const auto & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  415. auto nodeListIter = nodeList.begin();
  416. for(const auto * placeholder : placeholdersByPower)
  417. {
  418. if (nodeListIter == nodeList.end())
  419. break;
  420. if (!gameState->players.count(placeholder->getOwner()))
  421. continue; // illegal?
  422. // It looks like heroes placeholder by power can only be replaced for human player
  423. // Example where this is important: Spoils of War -> Greed
  424. // Meanwhile, placeholders by hero ID can be replaced for AI as well
  425. // Example: Armageddon's Blade -> To Kill A Hero
  426. if (!gameState->players.at(placeholder->getOwner()).isHuman())
  427. continue;
  428. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  429. nodeListIter++;
  430. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  431. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  432. }
  433. // Add remaining heroes without placeholders - to transfer their artifacts to placed heroes
  434. for (;nodeListIter != nodeList.end(); ++nodeListIter)
  435. {
  436. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  437. campaignHeroReplacements.emplace_back(hero, ObjectInstanceID::NONE);
  438. }
  439. }
  440. }
  441. void CGameStateCampaign::initHeroes()
  442. {
  443. auto chosenBonus = currentBonus();
  444. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != HeroTypeID::CAMP_GENERATED.getNum()) //exclude generated heroes
  445. {
  446. //find human player
  447. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  448. for (auto & elem : gameState->players)
  449. {
  450. if(elem.second.human)
  451. {
  452. humanPlayer = elem.first;
  453. break;
  454. }
  455. }
  456. assert(humanPlayer != PlayerColor::NEUTRAL);
  457. const auto & heroes = gameState->players.at(humanPlayer).getHeroes();
  458. if (chosenBonus->info1 == HeroTypeID::CAMP_STRONGEST.getNum()) //most powerful
  459. {
  460. int maxB = -1;
  461. for (int b=0; b<heroes.size(); ++b)
  462. {
  463. if (maxB == -1 || heroes[b]->getValueForCampaign() > heroes[maxB]->getValueForCampaign())
  464. {
  465. maxB = b;
  466. }
  467. }
  468. if(maxB < 0)
  469. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  470. else
  471. giveCampaignBonusToHero(heroes[maxB]);
  472. }
  473. else //specific hero
  474. {
  475. for (auto & hero : heroes)
  476. {
  477. if (hero->getHeroTypeID().getNum() == chosenBonus->info1)
  478. {
  479. giveCampaignBonusToHero(hero);
  480. break;
  481. }
  482. }
  483. }
  484. }
  485. auto campaignState = gameState->scenarioOps->campState;
  486. auto * yog = gameState->getUsedHero(HeroTypeID::SOLMYR);
  487. if (yog && boost::starts_with(campaignState->getFilename(), "DATA/YOG") && campaignState->currentScenario()->getNum() == 2)
  488. {
  489. assert(yog->isCampaignYog());
  490. gameState->giveHeroArtifact(yog, ArtifactID::ANGELIC_ALLIANCE);
  491. }
  492. transferMissingArtifacts(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  493. }
  494. void CGameStateCampaign::initStartingResources()
  495. {
  496. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  497. {
  498. std::vector<const PlayerSettings *> ret;
  499. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  500. {
  501. if(playerInfo.second.isControlledByHuman())
  502. ret.push_back(&playerInfo.second);
  503. }
  504. return ret;
  505. };
  506. auto chosenBonus = currentBonus();
  507. if(chosenBonus && chosenBonus->type == CampaignBonusType::RESOURCE)
  508. {
  509. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  510. for(const PlayerSettings *ps : people)
  511. {
  512. std::vector<GameResID> res; //resources we will give
  513. switch (chosenBonus->info1)
  514. {
  515. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  516. res.push_back(chosenBonus->info1);
  517. break;
  518. case EGameResID::COMMON: //wood+ore
  519. res.push_back(GameResID(EGameResID::WOOD));
  520. res.push_back(GameResID(EGameResID::ORE));
  521. break;
  522. case EGameResID::RARE: //rare
  523. res.push_back(GameResID(EGameResID::MERCURY));
  524. res.push_back(GameResID(EGameResID::SULFUR));
  525. res.push_back(GameResID(EGameResID::CRYSTAL));
  526. res.push_back(GameResID(EGameResID::GEMS));
  527. break;
  528. default:
  529. assert(0);
  530. break;
  531. }
  532. //increasing resource quantity
  533. for (auto & re : res)
  534. {
  535. gameState->players.at(ps->color).resources[re] += chosenBonus->info2;
  536. }
  537. }
  538. }
  539. }
  540. void CGameStateCampaign::initTowns()
  541. {
  542. auto chosenBonus = currentBonus();
  543. if (!chosenBonus)
  544. return;
  545. if (chosenBonus->type != CampaignBonusType::BUILDING)
  546. return;
  547. for (const auto & townID : gameState->map->getAllTowns())
  548. {
  549. auto town = gameState->getTown(townID);
  550. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  551. if (!owner)
  552. continue;
  553. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  554. if (!owner->human)
  555. continue;
  556. if (town->anchorPos() != pi.posOfMainTown)
  557. continue;
  558. BuildingID newBuilding;
  559. if(gameState->scenarioOps->campState->formatVCMI())
  560. newBuilding = BuildingID(chosenBonus->info1);
  561. else
  562. newBuilding = CBuildingHandler::campToERMU(chosenBonus->info1, town->getFactionID(), town->getBuildings());
  563. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  564. while(true)
  565. {
  566. if (newBuilding == BuildingID::NONE)
  567. break;
  568. if(town->hasBuilt(newBuilding))
  569. break;
  570. town->addBuilding(newBuilding);
  571. const auto & building = town->getTown()->buildings.at(newBuilding);
  572. newBuilding = building->upgrade;
  573. }
  574. break;
  575. }
  576. }
  577. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  578. {
  579. auto campaignBonus = currentBonus();
  580. if (!campaignBonus)
  581. return false;
  582. if(campaignBonus->type == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->info1))
  583. return true;
  584. return false;
  585. }
  586. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap()
  587. {
  588. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE, gameState->cb);
  589. }
  590. VCMI_LIB_NAMESPACE_END