CGameStateCampaign.cpp 21 KB

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