CGameStateCampaign.cpp 21 KB

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