CRewardableObject.cpp 16 KB

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