CGameStateCampaign.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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/hero/CHeroClass.h"
  19. #include "../entities/hero/CHero.h"
  20. #include "../mapping/CMapEditManager.h"
  21. #include "../mapObjects/CGHeroInstance.h"
  22. #include "../mapObjects/CGTownInstance.h"
  23. #include "../networkPacks/ArtifactLocation.h"
  24. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  26. #include "../StartInfo.h"
  27. #include "../mapping/CMap.h"
  28. #include "../CPlayerState.h"
  29. #include "mapping/MapFormatSettings.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->getType() == CampaignBonusType::HEROES_FROM_PREVIOUS_SCENARIO)
  59. return bonus->getValue<CampaignBonusHeroesFromScenario>().scenario;
  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. // Add spell flag to ensure that hero without spellbook won't receive one as part of initHero call
  169. for(auto & hero : campaignHeroReplacements)
  170. hero.hero->addSpellToSpellbook(SpellID::SPELLBOOK_PRESET);
  171. // Removing short-term bonuses
  172. for(auto & hero : campaignHeroReplacements)
  173. {
  174. hero.hero->removeBonusesRecursive(CSelector(Bonus::OneDay)
  175. .Or(CSelector(Bonus::OneWeek))
  176. .Or(CSelector(Bonus::NTurns))
  177. .Or(CSelector(Bonus::NDays))
  178. .Or(CSelector(Bonus::OneBattle)));
  179. }
  180. }
  181. void CGameStateCampaign::placeCampaignHeroes(vstd::RNG & randomGenerator)
  182. {
  183. // place bonus hero
  184. const auto & campaignState = gameState->scenarioOps->campState;
  185. const auto & campaignBonus = campaignState->getBonus(*campaignState->currentScenario());
  186. bool campaignGiveHero = campaignBonus && campaignBonus->getType() == CampaignBonusType::HERO;
  187. if(campaignGiveHero)
  188. {
  189. const auto & campaignBonusValue = campaignBonus->getValue<CampaignBonusStartingHero>();
  190. const auto & playerColor = campaignBonusValue.startingPlayer;
  191. const auto & it = gameState->scenarioOps->playerInfos.find(playerColor);
  192. if(it != gameState->scenarioOps->playerInfos.end())
  193. {
  194. HeroTypeID heroTypeId = campaignBonusValue.hero;
  195. if(heroTypeId == HeroTypeID::CAMP_RANDOM) // random bonus hero
  196. {
  197. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, playerColor);
  198. }
  199. gameState->placeStartingHero(playerColor, HeroTypeID(heroTypeId), gameState->map->players[playerColor.getNum()].posOfMainTown);
  200. }
  201. }
  202. logGlobal->debug("\tGenerate list of hero placeholders");
  203. generateCampaignHeroesToReplace();
  204. logGlobal->debug("\tPrepare crossover heroes");
  205. trimCrossoverHeroesParameters(randomGenerator, campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  206. // remove same heroes on the map which will be added through crossover heroes
  207. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  208. // with the same hero type id
  209. std::vector<std::shared_ptr<CGObjectInstance>> removedHeroes;
  210. std::set<HeroTypeID> reservedHeroes = campaignState->getReservedHeroes();
  211. std::set<HeroTypeID> heroesToRemove;
  212. for (auto const & heroID : reservedHeroes )
  213. {
  214. // Do not replace reserved heroes initially, e.g. in 1st campaign scenario in which they appear
  215. if (!campaignState->getHeroByType(heroID).isNull())
  216. heroesToRemove.insert(heroID);
  217. }
  218. for(auto & replacement : campaignHeroReplacements)
  219. if (replacement.heroPlaceholderId.hasValue())
  220. heroesToRemove.insert(replacement.hero->getHeroTypeID());
  221. for(auto & heroID : heroesToRemove)
  222. {
  223. auto * hero = gameState->getUsedHero(heroID);
  224. if(hero)
  225. {
  226. removedHeroes.push_back(gameState->map->eraseObject(hero->id));
  227. }
  228. }
  229. logGlobal->debug("\tReplace placeholders with heroes");
  230. replaceHeroesPlaceholders();
  231. // now add removed heroes again with unused type ID
  232. for(auto object : removedHeroes)
  233. {
  234. auto hero = dynamic_cast<CGHeroInstance*>(object.get());
  235. HeroTypeID heroTypeId;
  236. if(hero->ID == Obj::HERO)
  237. {
  238. heroTypeId = gameState->pickUnusedHeroTypeRandomly(randomGenerator, hero->tempOwner);
  239. }
  240. else if(hero->ID == Obj::PRISON)
  241. {
  242. auto unusedHeroTypeIds = gameState->getUnusedAllowedHeroes();
  243. if(!unusedHeroTypeIds.empty())
  244. {
  245. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, randomGenerator));
  246. }
  247. else
  248. {
  249. logGlobal->error("No free hero type ID found to replace prison.");
  250. assert(0);
  251. }
  252. }
  253. else
  254. {
  255. assert(0); // should not happen
  256. }
  257. hero->setHeroType(heroTypeId);
  258. gameState->map->getEditManager()->insertObject(object);
  259. }
  260. }
  261. void CGameStateCampaign::giveCampaignBonusToHero(CGHeroInstance * hero)
  262. {
  263. auto curBonus = currentBonus();
  264. if(!curBonus)
  265. return;
  266. assert(curBonus->isBonusForHero());
  267. //apply bonus
  268. switch(curBonus->getType())
  269. {
  270. case CampaignBonusType::SPELL:
  271. {
  272. const auto & bonusValue = curBonus->getValue<CampaignBonusSpell>();
  273. hero->addSpellToSpellbook(bonusValue.spell);
  274. break;
  275. }
  276. case CampaignBonusType::MONSTER:
  277. {
  278. const auto & bonusValue = curBonus->getValue<CampaignBonusCreatures>();
  279. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  280. {
  281. if(hero->slotEmpty(SlotID(i)))
  282. {
  283. hero->addToSlot(SlotID(i), bonusValue.creature, bonusValue.amount);
  284. break;
  285. }
  286. }
  287. break;
  288. }
  289. case CampaignBonusType::ARTIFACT:
  290. {
  291. const auto & bonusValue = curBonus->getValue<CampaignBonusArtifact>();
  292. if(!gameState->giveHeroArtifact(hero, bonusValue.artifact))
  293. logGlobal->error("Cannot give starting artifact - no free slots!");
  294. break;
  295. }
  296. case CampaignBonusType::SPELL_SCROLL:
  297. {
  298. const auto & bonusValue = curBonus->getValue<CampaignBonusSpellScroll>();
  299. const auto scroll = gameState->createScroll(bonusValue.spell);
  300. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  301. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  302. gameState->map->putArtifactInstance(*hero, scroll->getId(), slot);
  303. else
  304. logGlobal->error("Cannot give starting scroll - no free slots!");
  305. break;
  306. }
  307. case CampaignBonusType::PRIMARY_SKILL:
  308. {
  309. const auto & bonusValue = curBonus->getValue<CampaignBonusPrimarySkill>();
  310. for(auto skill : PrimarySkill::ALL_SKILLS())
  311. {
  312. int val = bonusValue.amounts[skill.getNum()];
  313. if(val == 0)
  314. continue;
  315. auto currentScenario = *gameState->scenarioOps->campState->currentScenario();
  316. auto bb = std::make_shared<Bonus>( BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, BonusSourceID(currentScenario), BonusSubtypeID(skill) );
  317. hero->addNewBonus(bb);
  318. }
  319. break;
  320. }
  321. case CampaignBonusType::SECONDARY_SKILL:
  322. {
  323. const auto & bonusValue = curBonus->getValue<CampaignBonusSecondarySkill>();
  324. hero->setSecSkillLevel(bonusValue.skill, bonusValue.mastery, ChangeValueMode::ABSOLUTE);
  325. break;
  326. }
  327. }
  328. }
  329. void CGameStateCampaign::replaceHeroesPlaceholders()
  330. {
  331. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  332. {
  333. if (!campaignHeroReplacement.heroPlaceholderId.hasValue())
  334. continue;
  335. auto heroPlaceholder = gameState->map->getObject(campaignHeroReplacement.heroPlaceholderId);
  336. auto heroToPlace = campaignHeroReplacement.hero;
  337. if(heroPlaceholder->tempOwner.isValidPlayer())
  338. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  339. heroToPlace->setAnchorPos(heroPlaceholder->anchorPos());
  340. heroToPlace->setHeroType(heroToPlace->getHeroTypeID());
  341. heroToPlace->appearance = heroToPlace->getObjectHandler()->getTemplates().front();
  342. heroToPlace->instanceName = heroPlaceholder->instanceName;
  343. gameState->map->replaceObject(campaignHeroReplacement.heroPlaceholderId, heroToPlace);
  344. }
  345. }
  346. void CGameStateCampaign::transferMissingArtifacts(const CampaignTravel & travelOptions)
  347. {
  348. CGHeroInstance * receiver = nullptr;
  349. for(auto hero : gameState->map->getObjects<CGHeroInstance>())
  350. {
  351. if (!hero->getOwner().isValidPlayer())
  352. continue; // prisons
  353. if (gameState->getPlayerState(hero->getOwner())->isHuman())
  354. {
  355. receiver = hero;
  356. break;
  357. }
  358. }
  359. assert(receiver);
  360. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  361. {
  362. if (campaignHeroReplacement.heroPlaceholderId.hasValue())
  363. continue;
  364. auto donorHero = campaignHeroReplacement.hero;
  365. if (!donorHero)
  366. throw std::runtime_error("Failed to find hero to take artifacts from! Scenario: " + gameState->map->name.toString());
  367. // process in reverse - 2nd artifact from a backpack must be processed before 1st one to avoid invalidation of artifact positions
  368. for (auto const & artLocation : boost::adaptors::reverse(campaignHeroReplacement.transferrableArtifacts))
  369. {
  370. auto * artifact = donorHero->getArt(artLocation);
  371. logGlobal->debug("Removing artifact %s from slot %d of hero %s for transfer", artifact->getType()->getJsonKey(), artLocation.getNum(), donorHero->getHeroTypeName());
  372. gameState->map->removeArtifactInstance(*donorHero, artLocation);
  373. if (receiver)
  374. {
  375. logGlobal->debug("Granting artifact %s to hero %s for transfer", artifact->getType()->getJsonKey(), receiver->getHeroTypeName());
  376. const auto slot = ArtifactUtils::getArtAnyPosition(receiver, artifact->getTypeId());
  377. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  378. gameState->map->putArtifactInstance(*receiver, artifact->getId(), slot);
  379. else
  380. logGlobal->error("Cannot transfer artifact - no free slots!");
  381. }
  382. else
  383. logGlobal->error("Cannot transfer artifact - no receiver hero!");
  384. }
  385. }
  386. }
  387. void CGameStateCampaign::generateCampaignHeroesToReplace()
  388. {
  389. auto campaignState = gameState->scenarioOps->campState;
  390. std::vector<CGHeroPlaceholder *> placeholdersByPower;
  391. std::vector<CGHeroPlaceholder *> placeholdersByType;
  392. campaignHeroReplacements.clear();
  393. // find all placeholders on map
  394. for(auto heroPlaceholder : gameState->map->getObjects<CGHeroPlaceholder>())
  395. {
  396. // only 1 field must be set
  397. assert(heroPlaceholder->powerRank.has_value() != heroPlaceholder->heroType.has_value());
  398. if(heroPlaceholder->powerRank)
  399. placeholdersByPower.push_back(heroPlaceholder);
  400. if(heroPlaceholder->heroType)
  401. placeholdersByType.push_back(heroPlaceholder);
  402. }
  403. //selecting heroes by type
  404. for(const auto * placeholder : placeholdersByType)
  405. {
  406. const auto & node = campaignState->getHeroByType(*placeholder->heroType);
  407. if (node.isNull())
  408. {
  409. logGlobal->info("Hero crossover: Unable to replace placeholder for %d (%s)!", placeholder->heroType->getNum(), LIBRARY->heroTypes()->getById(*placeholder->heroType)->getNameTranslated());
  410. continue;
  411. }
  412. auto hero = campaignState->crossoverDeserialize(node, gameState->map.get());
  413. logGlobal->info("Hero crossover: Loading placeholder for %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  414. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  415. }
  416. auto lastScenario = getHeroesSourceScenario();
  417. if (lastScenario)
  418. {
  419. // sort hero placeholders descending power
  420. boost::range::sort(placeholdersByPower, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  421. {
  422. return *a->powerRank > *b->powerRank;
  423. });
  424. const auto & nodeList = campaignState->getHeroesByPower(lastScenario.value());
  425. auto nodeListIter = nodeList.begin();
  426. for(const auto * placeholder : placeholdersByPower)
  427. {
  428. if (nodeListIter == nodeList.end())
  429. break;
  430. if (!gameState->players.count(placeholder->getOwner()))
  431. continue; // illegal?
  432. // It looks like heroes placeholder by power can only be replaced for human player
  433. // Example where this is important: Spoils of War -> Greed
  434. // Meanwhile, placeholders by hero ID can be replaced for AI as well
  435. // Example: Armageddon's Blade -> To Kill A Hero
  436. if (!gameState->players.at(placeholder->getOwner()).isHuman())
  437. continue;
  438. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  439. nodeListIter++;
  440. logGlobal->info("Hero crossover: Loading placeholder as %d (%s)", hero->getHeroType(), hero->getNameTranslated());
  441. campaignHeroReplacements.emplace_back(hero, placeholder->id);
  442. }
  443. // Add remaining heroes without placeholders - to transfer their artifacts to placed heroes
  444. for (;nodeListIter != nodeList.end(); ++nodeListIter)
  445. {
  446. auto hero = campaignState->crossoverDeserialize(*nodeListIter, gameState->map.get());
  447. campaignHeroReplacements.emplace_back(hero, ObjectInstanceID::NONE);
  448. }
  449. }
  450. }
  451. void CGameStateCampaign::initHeroes()
  452. {
  453. auto chosenBonus = currentBonus();
  454. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->getTargetedHero() != HeroTypeID::CAMP_GENERATED.getNum()) //exclude generated heroes
  455. {
  456. //find human player
  457. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  458. for (auto & elem : gameState->players)
  459. {
  460. if(elem.second.human)
  461. {
  462. humanPlayer = elem.first;
  463. break;
  464. }
  465. }
  466. assert(humanPlayer != PlayerColor::NEUTRAL);
  467. const auto & heroes = gameState->players.at(humanPlayer).getHeroes();
  468. if (chosenBonus->getTargetedHero() == HeroTypeID::CAMP_STRONGEST.getNum()) //most powerful
  469. {
  470. int maxB = -1;
  471. for (int b=0; b<heroes.size(); ++b)
  472. {
  473. if(maxB == -1 || CGHeroInstance::compareCampaignValue(heroes[b], heroes[maxB]))
  474. {
  475. maxB = b;
  476. }
  477. }
  478. if(maxB < 0)
  479. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  480. else
  481. giveCampaignBonusToHero(heroes[maxB]);
  482. }
  483. else //specific hero
  484. {
  485. for (auto & hero : heroes)
  486. {
  487. if (hero->getHeroTypeID().getNum() == chosenBonus->getTargetedHero())
  488. {
  489. giveCampaignBonusToHero(hero);
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. auto campaignState = gameState->scenarioOps->campState;
  496. if (campaignState->getYogWizardID().hasValue() && boost::starts_with(campaignState->getFilename(), "DATA/YOG") && campaignState->currentScenario()->getNum() == 2)
  497. {
  498. auto * yog = gameState->getUsedHero(campaignState->getYogWizardID());
  499. assert(yog);
  500. assert(yog->isCampaignYog());
  501. gameState->giveHeroArtifact(yog, ArtifactID::ANGELIC_ALLIANCE);
  502. }
  503. transferMissingArtifacts(campaignState->scenario(*campaignState->currentScenario()).travelOptions);
  504. }
  505. void CGameStateCampaign::initStartingResources()
  506. {
  507. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  508. {
  509. std::vector<const PlayerSettings *> ret;
  510. for(const auto & playerInfo : gameState->scenarioOps->playerInfos)
  511. {
  512. if(playerInfo.second.isControlledByHuman())
  513. ret.push_back(&playerInfo.second);
  514. }
  515. return ret;
  516. };
  517. const auto & chosenBonus = currentBonus();
  518. if(chosenBonus && chosenBonus->getType() == CampaignBonusType::RESOURCE)
  519. {
  520. const auto & bonusValue = chosenBonus->getValue<CampaignBonusStartingResources>();
  521. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  522. for(const PlayerSettings *ps : people)
  523. {
  524. std::vector<GameResID> res; //resources we will give
  525. switch (bonusValue.resource.toEnum())
  526. {
  527. case EGameResID::COMMON: //wood+ore
  528. res.push_back(GameResID(EGameResID::WOOD));
  529. res.push_back(GameResID(EGameResID::ORE));
  530. break;
  531. case EGameResID::RARE: //rare
  532. res.push_back(GameResID(EGameResID::MERCURY));
  533. res.push_back(GameResID(EGameResID::SULFUR));
  534. res.push_back(GameResID(EGameResID::CRYSTAL));
  535. res.push_back(GameResID(EGameResID::GEMS));
  536. break;
  537. default:
  538. res.push_back(bonusValue.resource);
  539. break;
  540. }
  541. for (auto & re : res)
  542. gameState->players.at(ps->color).resources[re] += bonusValue.amount;
  543. }
  544. }
  545. }
  546. void CGameStateCampaign::initTowns()
  547. {
  548. auto chosenBonus = currentBonus();
  549. if (!chosenBonus)
  550. return;
  551. if (chosenBonus->getType() != CampaignBonusType::BUILDING)
  552. return;
  553. const auto & bonusValue = chosenBonus->getValue<CampaignBonusBuilding>();
  554. for (const auto & townID : gameState->map->getAllTowns())
  555. {
  556. auto town = gameState->getTown(townID);
  557. PlayerState * owner = gameState->getPlayerState(town->getOwner());
  558. if (!owner)
  559. continue;
  560. PlayerInfo & pi = gameState->map->players[owner->color.getNum()];
  561. if (!owner->human)
  562. continue;
  563. if (town->anchorPos() != pi.posOfMainTown)
  564. continue;
  565. BuildingID newBuilding = bonusValue.buildingDecoded;
  566. if (bonusValue.buildingH3M.hasValue())
  567. {
  568. auto mapping = LIBRARY->mapFormat->getMapping(gameState->scenarioOps->campState->getFormat());
  569. newBuilding = mapping.remapBuilding(town->getFactionID(), bonusValue.buildingH3M);
  570. }
  571. // Build granted building & all prerequisites - e.g. Mages Guild Lvl 3 should also give Mages Guild Lvl 1 & 2
  572. while(true)
  573. {
  574. if (newBuilding == BuildingID::NONE)
  575. break;
  576. if(town->hasBuilt(newBuilding))
  577. break;
  578. town->addBuilding(newBuilding);
  579. const auto & building = town->getTown()->buildings.at(newBuilding);
  580. newBuilding = building->upgrade;
  581. }
  582. break;
  583. }
  584. }
  585. bool CGameStateCampaign::playerHasStartingHero(PlayerColor playerColor) const
  586. {
  587. auto campaignBonus = currentBonus();
  588. if (!campaignBonus)
  589. return false;
  590. if(campaignBonus->getType() == CampaignBonusType::HERO && playerColor == PlayerColor(campaignBonus->getValue<CampaignBonusStartingHero>().startingPlayer))
  591. return true;
  592. return false;
  593. }
  594. std::unique_ptr<CMap> CGameStateCampaign::getCurrentMap()
  595. {
  596. return gameState->scenarioOps->campState->getMap(CampaignScenarioID::NONE, gameState);
  597. }
  598. VCMI_LIB_NAMESPACE_END