Interface.cpp 14 KB

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