Interface.cpp 14 KB

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