Interface.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * Interface.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 "Interface.h"
  12. #include "../TerrainHandler.h"
  13. #include "../CPlayerState.h"
  14. #include "../CSoundBase.h"
  15. #include "../entities/hero/CHeroHandler.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include "../spells/ISpellMechanics.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../mapObjects/MiscObjects.h"
  21. #include "../mapping/CMapDefines.h"
  22. #include "../networkPacks/StackLocation.h"
  23. #include "../networkPacks/PacksForClient.h"
  24. #include "../IGameCallback.h"
  25. #include <vstd/RNG.h>
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. std::vector<ui32> Rewardable::Interface::getAvailableRewards(const CGHeroInstance * hero, Rewardable::EEventType event) const
  28. {
  29. std::vector<ui32> ret;
  30. for(size_t i = 0; i < configuration.info.size(); i++)
  31. {
  32. const Rewardable::VisitInfo & visit = configuration.info[i];
  33. if(event == visit.visitType && (!hero || visit.limiter.heroAllowed(hero)))
  34. ret.push_back(static_cast<ui32>(i));
  35. }
  36. return ret;
  37. }
  38. void Rewardable::Interface::grantRewardBeforeLevelup(const Rewardable::VisitInfo & info, const CGHeroInstance * hero) const
  39. {
  40. auto cb = getObject()->cb;
  41. assert(hero);
  42. assert(hero->tempOwner.isValidPlayer());
  43. assert(info.reward.creatures.size() <= GameConstants::ARMY_SIZE);
  44. cb->giveResources(hero->tempOwner, info.reward.resources);
  45. if (info.reward.revealTiles)
  46. {
  47. const auto & props = *info.reward.revealTiles;
  48. const auto functor = [&props](const TerrainTile * tile)
  49. {
  50. int score = 0;
  51. if (tile->getTerrain()->isSurface())
  52. score += props.scoreSurface;
  53. if (tile->getTerrain()->isUnderground())
  54. score += props.scoreSubterra;
  55. if (tile->getTerrain()->isWater())
  56. score += props.scoreWater;
  57. if (tile->getTerrain()->isRock())
  58. score += props.scoreRock;
  59. return score > 0;
  60. };
  61. std::unordered_set<int3> tiles;
  62. if (props.radius > 0)
  63. {
  64. cb->getTilesInRange(tiles, hero->getSightCenter(), props.radius, ETileVisibility::HIDDEN, hero->getOwner());
  65. if (props.hide)
  66. cb->getTilesInRange(tiles, hero->getSightCenter(), props.radius, ETileVisibility::REVEALED, hero->getOwner());
  67. vstd::erase_if(tiles, [&](const int3 & coord){
  68. return !functor(cb->getTile(coord));
  69. });
  70. }
  71. else
  72. {
  73. cb->getAllTiles(tiles, hero->tempOwner, -1, functor);
  74. }
  75. if (props.hide)
  76. {
  77. for (auto & player : cb->gameState().players)
  78. {
  79. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME && cb->getPlayerRelations(player.first, hero->getOwner()) == PlayerRelations::ENEMIES)
  80. cb->changeFogOfWar(tiles, player.first, ETileVisibility::HIDDEN);
  81. }
  82. }
  83. else
  84. {
  85. cb->changeFogOfWar(tiles, hero->getOwner(), ETileVisibility::REVEALED);
  86. }
  87. }
  88. for(const auto & entry : info.reward.secondary)
  89. {
  90. auto currentLevel = static_cast<MasteryLevel::Type>(hero->getSecSkillLevel(entry.first));
  91. if(currentLevel == MasteryLevel::EXPERT)
  92. continue;
  93. if(currentLevel != MasteryLevel::NONE || hero->canLearnSkill())
  94. cb->changeSecSkill(hero, entry.first, entry.second, false);
  95. }
  96. for(int i=0; i< info.reward.primary.size(); i++)
  97. if (info.reward.primary[i] != 0)
  98. cb->changePrimSkill(hero, static_cast<PrimarySkill>(i), info.reward.primary[i], false);
  99. TExpType expToGive = 0;
  100. if (info.reward.heroLevel > 0)
  101. expToGive += LIBRARY->heroh->reqExp(hero->level+info.reward.heroLevel) - LIBRARY->heroh->reqExp(hero->level);
  102. if (info.reward.heroExperience > 0)
  103. expToGive += hero->calculateXp(info.reward.heroExperience);
  104. if(expToGive)
  105. cb->giveExperience(hero, expToGive);
  106. }
  107. void Rewardable::Interface::grantRewardAfterLevelup(const Rewardable::VisitInfo & info, const CArmedInstance * army, const CGHeroInstance * hero) const
  108. {
  109. auto cb = getObject()->cb;
  110. if(info.reward.manaDiff || info.reward.manaPercentage >= 0)
  111. cb->setManaPoints(hero->id, info.reward.calculateManaPoints(hero));
  112. if(info.reward.movePoints || info.reward.movePercentage >= 0)
  113. {
  114. SetMovePoints smp;
  115. smp.hid = hero->id;
  116. smp.val = hero->movementPointsRemaining();
  117. if (info.reward.movePercentage >= 0) // percent from max
  118. smp.val = hero->movementPointsLimit(hero->inBoat() && hero->getBoat()->layer == EPathfindingLayer::SAIL) * info.reward.movePercentage / 100;
  119. smp.val = std::max<si32>(0, smp.val + info.reward.movePoints);
  120. cb->setMovePoints(&smp);
  121. }
  122. for(const Bonus & bonus : info.reward.heroBonuses)
  123. {
  124. GiveBonus gb(GiveBonus::ETarget::OBJECT, hero->id, bonus);
  125. cb->giveHeroBonus(&gb);
  126. }
  127. if (hero->getCommander())
  128. {
  129. for(const Bonus & bonus : info.reward.commanderBonuses)
  130. {
  131. GiveBonus gb(GiveBonus::ETarget::HERO_COMMANDER, hero->id, bonus);
  132. cb->giveHeroBonus(&gb);
  133. }
  134. }
  135. for(const Bonus & bonus : info.reward.playerBonuses)
  136. {
  137. GiveBonus gb(GiveBonus::ETarget::PLAYER, hero->getOwner(), bonus);
  138. cb->giveHeroBonus(&gb);
  139. }
  140. for(const ArtifactID & art : info.reward.takenArtifacts)
  141. {
  142. // hero does not have such artifact alone, but he might have it as part of assembled artifact
  143. if(!hero->hasArt(art))
  144. {
  145. const auto * assembly = hero->getCombinedArtWithPart(art);
  146. if (assembly)
  147. {
  148. DisassembledArtifact da;
  149. da.al = ArtifactLocation(hero->id, hero->getArtPos(assembly));
  150. cb->sendAndApply(da);
  151. }
  152. }
  153. if(hero->hasArt(art))
  154. cb->removeArtifact(ArtifactLocation(hero->id, hero->getArtPos(art, false)));
  155. }
  156. for(const ArtifactPosition & slot : info.reward.takenArtifactSlots)
  157. {
  158. const auto & slotContent = hero->getSlot(slot);
  159. if (!slotContent->locked && slotContent->artifactID.hasValue())
  160. cb->removeArtifact(ArtifactLocation(hero->id, slot));
  161. // TODO: handle locked slots?
  162. }
  163. for(const SpellID & spell : info.reward.takenScrolls)
  164. {
  165. if(hero->hasScroll(spell, false))
  166. cb->removeArtifact(ArtifactLocation(hero->id, hero->getScrollPos(spell, false)));
  167. }
  168. for(const ArtifactID & art : info.reward.grantedArtifacts)
  169. cb->giveHeroNewArtifact(hero, art, ArtifactPosition::FIRST_AVAILABLE);
  170. for(const SpellID & spell : info.reward.grantedScrolls)
  171. cb->giveHeroNewScroll(hero, spell, ArtifactPosition::FIRST_AVAILABLE);
  172. if(!info.reward.spells.empty())
  173. {
  174. std::set<SpellID> spellsToGive;
  175. for (auto const & spell : info.reward.spells)
  176. if (hero->canLearnSpell(spell.toEntity(LIBRARY), true))
  177. spellsToGive.insert(spell);
  178. if (!spellsToGive.empty())
  179. cb->changeSpells(hero, true, spellsToGive);
  180. }
  181. if (!info.reward.takenCreatures.empty())
  182. {
  183. cb->takeCreatures(hero->id, info.reward.takenCreatures, !info.reward.creatures.empty());
  184. }
  185. if(!info.reward.creaturesChange.empty())
  186. {
  187. for(const auto & slot : hero->Slots())
  188. {
  189. const auto & heroStack = slot.second;
  190. for(const auto & change : info.reward.creaturesChange)
  191. {
  192. if (heroStack->getId() == change.first)
  193. {
  194. StackLocation location(hero->id, slot.first);
  195. cb->changeStackType(location, change.second.toCreature());
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. if(!info.reward.creatures.empty())
  202. {
  203. CCreatureSet creatures;
  204. for(const auto & crea : info.reward.creatures)
  205. creatures.addToSlot(creatures.getFreeSlot(), std::make_unique<CStackInstance>(cb, crea.getId(), crea.getCount()));
  206. if(auto * army = dynamic_cast<const CArmedInstance*>(this)) //TODO: to fix that, CArmedInstance must be split on map instance part and interface part
  207. cb->giveCreatures(army, hero, creatures, false);
  208. }
  209. if(info.reward.spellCast.first != SpellID::NONE)
  210. {
  211. caster.setActualCaster(hero);
  212. caster.setSpellSchoolLevel(info.reward.spellCast.second);
  213. cb->castSpell(&caster, info.reward.spellCast.first, int3{-1, -1, -1});
  214. }
  215. if(info.reward.removeObject)
  216. if(auto * instance = dynamic_cast<const CGObjectInstance*>(this))
  217. cb->removeAfterVisit(instance->id);
  218. }
  219. void Rewardable::Interface::serializeJson(JsonSerializeFormat & handler)
  220. {
  221. configuration.serializeJson(handler);
  222. }
  223. void Rewardable::Interface::grantRewardWithMessage(const CGHeroInstance * contextHero, int index, bool markAsVisit) const
  224. {
  225. auto vi = configuration.info.at(index);
  226. logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString());
  227. // show message only if it is not empty or in infobox
  228. if (configuration.infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
  229. {
  230. InfoWindow iw;
  231. iw.player = contextHero->tempOwner;
  232. iw.text = vi.message;
  233. vi.reward.loadComponents(iw.components, contextHero);
  234. iw.type = configuration.infoWindowType;
  235. if(!iw.components.empty() || !iw.text.toString().empty())
  236. getObject()->cb->showInfoDialog(&iw);
  237. }
  238. // grant reward afterwards. Note that it may remove object
  239. if(markAsVisit)
  240. markAsVisited(contextHero);
  241. grantReward(index, contextHero);
  242. }
  243. void Rewardable::Interface::selectRewardWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, const MetaString & dialog) const
  244. {
  245. BlockingDialog sd(configuration.canRefuse, rewardIndices.size() > 1);
  246. sd.player = contextHero->tempOwner;
  247. sd.text = dialog;
  248. sd.components = loadComponents(contextHero, rewardIndices);
  249. getObject()->cb->showBlockingDialog(getObject(), &sd);
  250. }
  251. std::vector<Component> Rewardable::Interface::loadComponents(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices) const
  252. {
  253. std::vector<Component> result;
  254. if (rewardIndices.empty())
  255. return result;
  256. if (configuration.selectMode != Rewardable::SELECT_FIRST && rewardIndices.size() > 1)
  257. {
  258. for (auto index : rewardIndices)
  259. result.push_back(configuration.info.at(index).reward.getDisplayedComponent(contextHero));
  260. }
  261. else
  262. {
  263. configuration.info.at(rewardIndices.front()).reward.loadComponents(result, contextHero);
  264. }
  265. return result;
  266. }
  267. void Rewardable::Interface::grantAllRewardsWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, bool markAsVisit) const
  268. {
  269. if (rewardIndices.empty())
  270. return;
  271. for (auto index : rewardIndices)
  272. {
  273. // TODO: Merge all rewards of same type, with single message?
  274. grantRewardWithMessage(contextHero, index, false);
  275. }
  276. // Mark visited only after all rewards were processed
  277. if(markAsVisit)
  278. markAsVisited(contextHero);
  279. }
  280. void Rewardable::Interface::doHeroVisit(const CGHeroInstance *h) const
  281. {
  282. if(!wasVisitedBefore(h))
  283. {
  284. auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT);
  285. bool objectRemovalPossible = false;
  286. for(auto index : rewards)
  287. {
  288. if(configuration.info.at(index).reward.removeObject)
  289. objectRemovalPossible = true;
  290. }
  291. logGlobal->debug("Visiting object with %d possible rewards", rewards.size());
  292. switch (rewards.size())
  293. {
  294. case 0: // no available rewards, e.g. visiting School of War without gold
  295. {
  296. auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
  297. if (!emptyRewards.empty())
  298. grantRewardWithMessage(h, emptyRewards[0], false);
  299. else
  300. logMod->warn("No applicable message for visiting empty object!");
  301. break;
  302. }
  303. case 1: // one reward. Just give it with message
  304. {
  305. if (configuration.canRefuse)
  306. selectRewardWithMessage(h, rewards, configuration.info.at(rewards.front()).message);
  307. else
  308. grantRewardWithMessage(h, rewards.front(), true);
  309. break;
  310. }
  311. default: // multiple rewards. Act according to select mode
  312. {
  313. switch (configuration.selectMode) {
  314. case Rewardable::SELECT_PLAYER: // player must select
  315. selectRewardWithMessage(h, rewards, configuration.onSelect);
  316. break;
  317. case Rewardable::SELECT_FIRST: // give first available
  318. if (configuration.canRefuse)
  319. selectRewardWithMessage(h, { rewards.front() }, configuration.info.at(rewards.front()).message);
  320. else
  321. grantRewardWithMessage(h, rewards.front(), true);
  322. break;
  323. case Rewardable::SELECT_RANDOM: // give random
  324. {
  325. ui32 rewardIndex = *RandomGeneratorUtil::nextItem(rewards, getObject()->cb->getRandomGenerator());
  326. if (configuration.canRefuse)
  327. selectRewardWithMessage(h, { rewardIndex }, configuration.info.at(rewardIndex).message);
  328. else
  329. grantRewardWithMessage(h, rewardIndex, true);
  330. break;
  331. }
  332. case Rewardable::SELECT_ALL: // grant all possible
  333. grantAllRewardsWithMessage(h, rewards, true);
  334. break;
  335. }
  336. break;
  337. }
  338. }
  339. if(!objectRemovalPossible && getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  340. markAsScouted(h);
  341. }
  342. else
  343. {
  344. logGlobal->debug("Revisiting already visited object");
  345. if (!wasVisited(h->getOwner()))
  346. markAsScouted(h);
  347. auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED);
  348. if (!visitedRewards.empty())
  349. grantRewardWithMessage(h, visitedRewards[0], false);
  350. else
  351. logMod->warn("No applicable message for visiting already visited object!");
  352. }
  353. }
  354. void Rewardable::Interface::onBlockingDialogAnswered(const CGHeroInstance * hero, int32_t answer) const
  355. {
  356. if (answer == 0)
  357. return; //Player refused
  358. if(answer > 0 && answer - 1 < configuration.info.size())
  359. {
  360. auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  361. markAsVisited(hero);
  362. grantReward(list[answer - 1], hero);
  363. }
  364. else
  365. {
  366. throw std::runtime_error("Unhandled choice");
  367. }
  368. }
  369. VCMI_LIB_NAMESPACE_END