CGameStateCampaign.cpp 21 KB

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