CRewardableObject.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * CRewardableObject.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 "CRewardableObject.h"
  12. #include "../CPlayerState.h"
  13. #include "../GameSettings.h"
  14. #include "../IGameCallback.h"
  15. #include "../battle/BattleLayout.h"
  16. #include "../gameState/CGameState.h"
  17. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  18. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  19. #include "../mapObjectConstructors/CRewardableConstructor.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../networkPacks/PacksForClient.h"
  22. #include "../networkPacks/PacksForClientBattle.h"
  23. #include "../serializer/JsonSerializeFormat.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include <vstd/RNG.h>
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. void CRewardableObject::grantRewardWithMessage(const CGHeroInstance * contextHero, int index, bool markAsVisit) const
  28. {
  29. auto vi = configuration.info.at(index);
  30. logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString());
  31. // show message only if it is not empty or in infobox
  32. if (configuration.infoWindowType != EInfoWindowMode::MODAL || !vi.message.toString().empty())
  33. {
  34. InfoWindow iw;
  35. iw.player = contextHero->tempOwner;
  36. iw.text = vi.message;
  37. vi.reward.loadComponents(iw.components, contextHero);
  38. iw.type = configuration.infoWindowType;
  39. if(!iw.components.empty() || !iw.text.toString().empty())
  40. cb->showInfoDialog(&iw);
  41. }
  42. // grant reward afterwards. Note that it may remove object
  43. if(markAsVisit)
  44. markAsVisited(contextHero);
  45. grantReward(index, contextHero);
  46. }
  47. void CRewardableObject::selectRewardWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, const MetaString & dialog) const
  48. {
  49. BlockingDialog sd(configuration.canRefuse, rewardIndices.size() > 1);
  50. sd.player = contextHero->tempOwner;
  51. sd.text = dialog;
  52. sd.components = loadComponents(contextHero, rewardIndices);
  53. cb->showBlockingDialog(this, &sd);
  54. }
  55. void CRewardableObject::grantAllRewardsWithMessage(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices, bool markAsVisit) const
  56. {
  57. if (rewardIndices.empty())
  58. return;
  59. for (auto index : rewardIndices)
  60. {
  61. // TODO: Merge all rewards of same type, with single message?
  62. grantRewardWithMessage(contextHero, index, false);
  63. }
  64. // Mark visited only after all rewards were processed
  65. if(markAsVisit)
  66. markAsVisited(contextHero);
  67. }
  68. std::vector<Component> CRewardableObject::loadComponents(const CGHeroInstance * contextHero, const std::vector<ui32> & rewardIndices) const
  69. {
  70. std::vector<Component> result;
  71. if (rewardIndices.empty())
  72. return result;
  73. if (configuration.selectMode != Rewardable::SELECT_FIRST && rewardIndices.size() > 1)
  74. {
  75. for (auto index : rewardIndices)
  76. result.push_back(configuration.info.at(index).reward.getDisplayedComponent(contextHero));
  77. }
  78. else
  79. {
  80. configuration.info.at(rewardIndices.front()).reward.loadComponents(result, contextHero);
  81. }
  82. return result;
  83. }
  84. bool CRewardableObject::isGuarded() const
  85. {
  86. return stacksCount() > 0;
  87. }
  88. void CRewardableObject::onHeroVisit(const CGHeroInstance *hero) const
  89. {
  90. if(!wasScouted(hero->getOwner()))
  91. {
  92. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_SCOUTED, id, hero->id);
  93. cb->sendAndApply(&cov);
  94. }
  95. if (isGuarded())
  96. {
  97. auto guardedIndexes = getAvailableRewards(hero, Rewardable::EEventType::EVENT_GUARDED);
  98. auto guardedReward = configuration.info.at(guardedIndexes.at(0));
  99. // ask player to confirm attack
  100. BlockingDialog bd(true, false);
  101. bd.player = hero->getOwner();
  102. bd.text = guardedReward.message;
  103. bd.components = getPopupComponents(hero->getOwner());
  104. cb->showBlockingDialog(this, &bd);
  105. }
  106. else
  107. {
  108. doHeroVisit(hero);
  109. }
  110. }
  111. void CRewardableObject::doHeroVisit(const CGHeroInstance *h) const
  112. {
  113. if(!wasVisitedBefore(h))
  114. {
  115. auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT);
  116. bool objectRemovalPossible = false;
  117. for(auto index : rewards)
  118. {
  119. if(configuration.info.at(index).reward.removeObject)
  120. objectRemovalPossible = true;
  121. }
  122. logGlobal->debug("Visiting object with %d possible rewards", rewards.size());
  123. switch (rewards.size())
  124. {
  125. case 0: // no available rewards, e.g. visiting School of War without gold
  126. {
  127. auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE);
  128. if (!emptyRewards.empty())
  129. grantRewardWithMessage(h, emptyRewards[0], false);
  130. else
  131. logMod->warn("No applicable message for visiting empty object!");
  132. break;
  133. }
  134. case 1: // one reward. Just give it with message
  135. {
  136. if (configuration.canRefuse)
  137. selectRewardWithMessage(h, rewards, configuration.info.at(rewards.front()).message);
  138. else
  139. grantRewardWithMessage(h, rewards.front(), true);
  140. break;
  141. }
  142. default: // multiple rewards. Act according to select mode
  143. {
  144. switch (configuration.selectMode) {
  145. case Rewardable::SELECT_PLAYER: // player must select
  146. selectRewardWithMessage(h, rewards, configuration.onSelect);
  147. break;
  148. case Rewardable::SELECT_FIRST: // give first available
  149. if (configuration.canRefuse)
  150. selectRewardWithMessage(h, { rewards.front() }, configuration.info.at(rewards.front()).message);
  151. else
  152. grantRewardWithMessage(h, rewards.front(), true);
  153. break;
  154. case Rewardable::SELECT_RANDOM: // give random
  155. {
  156. ui32 rewardIndex = *RandomGeneratorUtil::nextItem(rewards, cb->gameState()->getRandomGenerator());
  157. if (configuration.canRefuse)
  158. selectRewardWithMessage(h, { rewardIndex }, configuration.info.at(rewardIndex).message);
  159. else
  160. grantRewardWithMessage(h, rewardIndex, true);
  161. break;
  162. }
  163. case Rewardable::SELECT_ALL: // grant all possible
  164. grantAllRewardsWithMessage(h, rewards, true);
  165. break;
  166. }
  167. break;
  168. }
  169. }
  170. if(!objectRemovalPossible && getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  171. {
  172. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_PLAYER, id, h->id);
  173. cb->sendAndApply(&cov);
  174. }
  175. }
  176. else
  177. {
  178. logGlobal->debug("Revisiting already visited object");
  179. if (!wasVisited(h->getOwner()))
  180. {
  181. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_PLAYER, id, h->id);
  182. cb->sendAndApply(&cov);
  183. }
  184. auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED);
  185. if (!visitedRewards.empty())
  186. grantRewardWithMessage(h, visitedRewards[0], false);
  187. else
  188. logMod->warn("No applicable message for visiting already visited object!");
  189. }
  190. }
  191. void CRewardableObject::heroLevelUpDone(const CGHeroInstance *hero) const
  192. {
  193. grantRewardAfterLevelup(cb, configuration.info.at(selectedReward), this, hero);
  194. }
  195. void CRewardableObject::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  196. {
  197. if (result.winner == BattleSide::ATTACKER)
  198. {
  199. doHeroVisit(hero);
  200. }
  201. }
  202. void CRewardableObject::blockingDialogAnswered(const CGHeroInstance * hero, int32_t answer) const
  203. {
  204. if(isGuarded())
  205. {
  206. if (answer)
  207. {
  208. auto layout = BattleLayout::createLayout(cb, configuration.guardsLayout, hero, this);
  209. cb->startBattle(hero, this, visitablePos(), hero, nullptr, layout, nullptr);
  210. }
  211. }
  212. else
  213. {
  214. if (answer == 0)
  215. return; //Player refused
  216. if(answer > 0 && answer - 1 < configuration.info.size())
  217. {
  218. auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  219. markAsVisited(hero);
  220. grantReward(list[answer - 1], hero);
  221. }
  222. else
  223. {
  224. throw std::runtime_error("Unhandled choice");
  225. }
  226. }
  227. }
  228. void CRewardableObject::markAsVisited(const CGHeroInstance * hero) const
  229. {
  230. cb->setObjPropertyValue(id, ObjProperty::REWARD_CLEARED, true);
  231. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_ADD_HERO, id, hero->id);
  232. cb->sendAndApply(&cov);
  233. }
  234. void CRewardableObject::grantReward(ui32 rewardID, const CGHeroInstance * hero) const
  235. {
  236. cb->setObjPropertyValue(id, ObjProperty::REWARD_SELECT, rewardID);
  237. grantRewardBeforeLevelup(cb, configuration.info.at(rewardID), hero);
  238. // hero is not blocked by levelup dialog - grant remainder immediately
  239. if(!cb->isVisitCoveredByAnotherQuery(this, hero))
  240. {
  241. grantRewardAfterLevelup(cb, configuration.info.at(rewardID), this, hero);
  242. }
  243. }
  244. bool CRewardableObject::wasVisitedBefore(const CGHeroInstance * contextHero) const
  245. {
  246. switch (configuration.visitMode)
  247. {
  248. case Rewardable::VISIT_UNLIMITED:
  249. return false;
  250. case Rewardable::VISIT_ONCE:
  251. return onceVisitableObjectCleared;
  252. case Rewardable::VISIT_PLAYER:
  253. return vstd::contains(cb->getPlayerState(contextHero->getOwner())->visitedObjects, ObjectInstanceID(id));
  254. case Rewardable::VISIT_BONUS:
  255. return contextHero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID));
  256. case Rewardable::VISIT_HERO:
  257. return contextHero->visitedObjects.count(ObjectInstanceID(id));
  258. case Rewardable::VISIT_LIMITER:
  259. return configuration.visitLimiter.heroAllowed(contextHero);
  260. default:
  261. return false;
  262. }
  263. }
  264. bool CRewardableObject::wasVisited(PlayerColor player) const
  265. {
  266. switch (configuration.visitMode)
  267. {
  268. case Rewardable::VISIT_UNLIMITED:
  269. case Rewardable::VISIT_BONUS:
  270. case Rewardable::VISIT_HERO:
  271. case Rewardable::VISIT_LIMITER:
  272. return false;
  273. case Rewardable::VISIT_ONCE:
  274. case Rewardable::VISIT_PLAYER:
  275. return vstd::contains(cb->getPlayerState(player)->visitedObjects, ObjectInstanceID(id));
  276. default:
  277. return false;
  278. }
  279. }
  280. bool CRewardableObject::wasScouted(PlayerColor player) const
  281. {
  282. return vstd::contains(cb->getPlayerTeam(player)->scoutedObjects, ObjectInstanceID(id));
  283. }
  284. bool CRewardableObject::wasVisited(const CGHeroInstance * h) const
  285. {
  286. switch (configuration.visitMode)
  287. {
  288. case Rewardable::VISIT_BONUS:
  289. return h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID));
  290. case Rewardable::VISIT_HERO:
  291. return h->visitedObjects.count(ObjectInstanceID(id));
  292. case Rewardable::VISIT_LIMITER:
  293. return wasScouted(h->getOwner()) && configuration.visitLimiter.heroAllowed(h);
  294. default:
  295. return wasVisited(h->getOwner());
  296. }
  297. }
  298. std::string CRewardableObject::getDisplayTextImpl(PlayerColor player, const CGHeroInstance * hero, bool includeDescription) const
  299. {
  300. std::string result = getObjectName();
  301. if (includeDescription && !getDescriptionMessage(player, hero).empty())
  302. result += "\n" + getDescriptionMessage(player, hero);
  303. if (hero)
  304. {
  305. if(configuration.visitMode != Rewardable::VISIT_UNLIMITED)
  306. {
  307. if (wasVisited(hero))
  308. result += "\n" + configuration.visitedTooltip.toString();
  309. else
  310. result += "\n " + configuration.notVisitedTooltip.toString();
  311. }
  312. }
  313. else
  314. {
  315. if(configuration.visitMode == Rewardable::VISIT_PLAYER || configuration.visitMode == Rewardable::VISIT_ONCE)
  316. {
  317. if (wasVisited(player))
  318. result += "\n" + configuration.visitedTooltip.toString();
  319. else
  320. result += "\n" + configuration.notVisitedTooltip.toString();
  321. }
  322. }
  323. return result;
  324. }
  325. std::string CRewardableObject::getHoverText(PlayerColor player) const
  326. {
  327. return getDisplayTextImpl(player, nullptr, false);
  328. }
  329. std::string CRewardableObject::getHoverText(const CGHeroInstance * hero) const
  330. {
  331. return getDisplayTextImpl(hero->getOwner(), hero, false);
  332. }
  333. std::string CRewardableObject::getPopupText(PlayerColor player) const
  334. {
  335. return getDisplayTextImpl(player, nullptr, true);
  336. }
  337. std::string CRewardableObject::getPopupText(const CGHeroInstance * hero) const
  338. {
  339. return getDisplayTextImpl(hero->getOwner(), hero, true);
  340. }
  341. std::string CRewardableObject::getDescriptionMessage(PlayerColor player, const CGHeroInstance * hero) const
  342. {
  343. if (!wasScouted(player) || configuration.info.empty())
  344. return configuration.description.toString();
  345. auto rewardIndices = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  346. if (rewardIndices.empty() || !configuration.info[0].description.empty())
  347. return configuration.info[0].description.toString();
  348. if (!configuration.info[rewardIndices.front()].description.empty())
  349. return configuration.info[rewardIndices.front()].description.toString();
  350. return configuration.description.toString();
  351. }
  352. std::vector<Component> CRewardableObject::getPopupComponentsImpl(PlayerColor player, const CGHeroInstance * hero) const
  353. {
  354. if (!wasScouted(player))
  355. return {};
  356. if (isGuarded())
  357. {
  358. if (!cb->getSettings().getBoolean(EGameSettings::BANKS_SHOW_GUARDS_COMPOSITION))
  359. return {};
  360. std::map<CreatureID, int> guardsAmounts;
  361. std::vector<Component> result;
  362. for (auto const & slot : Slots())
  363. if (slot.second)
  364. guardsAmounts[slot.second->getCreatureID()] += slot.second->getCount();
  365. for (auto const & guard : guardsAmounts)
  366. {
  367. Component comp(ComponentType::CREATURE, guard.first, guard.second);
  368. result.push_back(comp);
  369. }
  370. return result;
  371. }
  372. else
  373. {
  374. if (!configuration.showScoutedPreview)
  375. return {};
  376. auto rewardIndices = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT);
  377. if (rewardIndices.empty() && !configuration.info.empty())
  378. {
  379. // Object has valid config, but current hero has no rewards that he can receive.
  380. // Usually this happens if hero has already visited this object -> show reward using context without any hero
  381. // since reward may be context-sensitive - e.g. Witch Hut that gives 1 skill, but always at basic level
  382. return loadComponents(nullptr, {0});
  383. }
  384. if (rewardIndices.empty())
  385. return {};
  386. return loadComponents(hero, rewardIndices);
  387. }
  388. }
  389. std::vector<Component> CRewardableObject::getPopupComponents(PlayerColor player) const
  390. {
  391. return getPopupComponentsImpl(player, nullptr);
  392. }
  393. std::vector<Component> CRewardableObject::getPopupComponents(const CGHeroInstance * hero) const
  394. {
  395. return getPopupComponentsImpl(hero->getOwner(), hero);
  396. }
  397. void CRewardableObject::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  398. {
  399. switch (what)
  400. {
  401. case ObjProperty::REWARD_SELECT:
  402. selectedReward = identifier.getNum();
  403. break;
  404. case ObjProperty::REWARD_CLEARED:
  405. onceVisitableObjectCleared = identifier.getNum();
  406. break;
  407. }
  408. }
  409. void CRewardableObject::newTurn(vstd::RNG & rand) const
  410. {
  411. if (configuration.resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % configuration.resetParameters.period) == 0)
  412. {
  413. if (configuration.resetParameters.rewards)
  414. {
  415. auto handler = std::dynamic_pointer_cast<const CRewardableConstructor>(getObjectHandler());
  416. auto newConfiguration = handler->generateConfiguration(cb, rand, ID);
  417. cb->setRewardableObjectConfiguration(id, newConfiguration);
  418. }
  419. if (configuration.resetParameters.visitors)
  420. {
  421. cb->setObjPropertyValue(id, ObjProperty::REWARD_CLEARED, false);
  422. ChangeObjectVisitors cov(ChangeObjectVisitors::VISITOR_CLEAR, id);
  423. cb->sendAndApply(&cov);
  424. }
  425. }
  426. }
  427. void CRewardableObject::initObj(vstd::RNG & rand)
  428. {
  429. getObjectHandler()->configureObject(this, rand);
  430. }
  431. CRewardableObject::CRewardableObject(IGameCallback *cb)
  432. :CArmedInstance(cb)
  433. {}
  434. void CRewardableObject::serializeJsonOptions(JsonSerializeFormat & handler)
  435. {
  436. CArmedInstance::serializeJsonOptions(handler);
  437. handler.serializeStruct("rewardable", static_cast<Rewardable::Interface&>(*this));
  438. }
  439. void CRewardableObject::initializeGuards()
  440. {
  441. clearSlots();
  442. // Workaround for default creature banks strings that has placeholder for object name
  443. // TODO: find better location for this code
  444. for (auto & visitInfo : configuration.info)
  445. visitInfo.message.replaceRawString(getObjectName());
  446. for (auto const & visitInfo : configuration.info)
  447. {
  448. for (auto const & guard : visitInfo.reward.guards)
  449. {
  450. auto slotID = getFreeSlot();
  451. if (!slotID.validSlot())
  452. return;
  453. putStack(slotID, new CStackInstance(guard.getId(), guard.getCount()));
  454. }
  455. }
  456. }
  457. bool CRewardableObject::isCoastVisitable() const
  458. {
  459. return configuration.coastVisitable;
  460. }
  461. VCMI_LIB_NAMESPACE_END