CQuest.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /*
  2. * CQuest.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 "CQuest.h"
  12. #include <vcmi/spells/Spell.h>
  13. #include "../CSoundBase.h"
  14. #include "../texts/CGeneralTextHandler.h"
  15. #include "CGCreature.h"
  16. #include "../IGameSettings.h"
  17. #include "../callback/IGameInfoCallback.h"
  18. #include "../callback/IGameEventCallback.h"
  19. #include "../callback/IGameRandomizer.h"
  20. #include "../entities/artifact/CArtifact.h"
  21. #include "../entities/hero/CHeroHandler.h"
  22. #include "../entities/ResourceTypeHandler.h"
  23. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  24. #include "../serializer/JsonSerializeFormat.h"
  25. #include "../GameConstants.h"
  26. #include "../constants/StringConstants.h"
  27. #include "../CPlayerState.h"
  28. #include "../CSkillHandler.h"
  29. #include "../mapping/CMap.h"
  30. #include "../mapObjects/CGHeroInstance.h"
  31. #include "../modding/ModScope.h"
  32. #include "../modding/ModUtility.h"
  33. #include "../networkPacks/PacksForClient.h"
  34. #include "../spells/CSpellHandler.h"
  35. #include <vstd/RNG.h>
  36. VCMI_LIB_NAMESPACE_BEGIN
  37. //TODO: Remove constructor
  38. CQuest::CQuest():
  39. qid(-1),
  40. isCompleted(false),
  41. lastDay(-1),
  42. killTarget(ObjectInstanceID::NONE),
  43. textOption(0),
  44. completedOption(0),
  45. stackDirection(0),
  46. isCustomFirst(false),
  47. isCustomNext(false),
  48. isCustomComplete(false),
  49. repeatedQuest(false),
  50. questName(CQuest::missionName(EQuestMission::NONE))
  51. {
  52. }
  53. static std::string visitedTxt(const bool visited)
  54. {
  55. int id = visited ? 352 : 353;
  56. return LIBRARY->generaltexth->allTexts[id];
  57. }
  58. const std::string & CQuest::missionName(EQuestMission mission)
  59. {
  60. static const std::array<std::string, 14> names = {
  61. "empty",
  62. "heroLevel",
  63. "primarySkill",
  64. "killHero",
  65. "killCreature",
  66. "bringArt",
  67. "bringCreature",
  68. "bringResources",
  69. "bringHero",
  70. "bringPlayer",
  71. "hotaINVALID", // only used for h3m parsing
  72. "keymaster",
  73. "heroClass",
  74. "reachDate"
  75. };
  76. if(static_cast<size_t>(mission) < names.size())
  77. return names[static_cast<size_t>(mission)];
  78. return names[0];
  79. }
  80. const std::string & CQuest::missionState(int state)
  81. {
  82. static const std::array<std::string, 5> states = {
  83. "receive",
  84. "visit",
  85. "complete",
  86. "hover",
  87. "description",
  88. };
  89. if(state < states.size())
  90. return states[state];
  91. return states[0];
  92. }
  93. bool CQuest::checkMissionArmy(const CQuest * q, const CCreatureSet * army)
  94. {
  95. return army->hasUnits(q->mission.creatures, true);
  96. }
  97. bool CQuest::checkQuest(const CGHeroInstance * h) const
  98. {
  99. if(!mission.heroAllowed(h))
  100. return false;
  101. if(killTarget.hasValue())
  102. {
  103. PlayerColor owner = h->getOwner();
  104. if (!h->cb->getPlayerState(owner)->destroyedObjects.count(killTarget))
  105. return false;
  106. }
  107. return true;
  108. }
  109. void CQuest::completeQuest(IGameEventCallback & gameEvents, const CGHeroInstance *h, bool allowFullArmyRemoval) const
  110. {
  111. // FIXME: this should be part of 'reward', and not hacking into limiter state that should only limit access to such reward
  112. for(auto & elem : mission.artifacts)
  113. {
  114. if(h->hasArt(elem))
  115. {
  116. gameEvents.removeArtifact(ArtifactLocation(h->id, h->getArtPos(elem, false)));
  117. continue;
  118. }
  119. // perhaps artifact is part of a combined artifact?
  120. const auto * assembly = h->getCombinedArtWithPart(elem);
  121. if (assembly)
  122. {
  123. auto parts = assembly->getPartsInfo();
  124. // Remove the assembly
  125. gameEvents.removeArtifact(ArtifactLocation(h->id, h->getArtPos(assembly)));
  126. // Disassemble this backpack artifact
  127. for(const auto & ci : parts)
  128. {
  129. if(ci.getArtifact()->getTypeId() != elem)
  130. gameEvents.giveHeroNewArtifact(h, ci.getArtifact()->getTypeId(), ArtifactPosition::BACKPACK_START);
  131. }
  132. continue;
  133. }
  134. logGlobal->error("Failed to find artifact %s in inventory of hero %s", elem.toEntity(LIBRARY)->getJsonKey(), h->getHeroTypeID());
  135. }
  136. gameEvents.takeCreatures(h->id, mission.creatures, allowFullArmyRemoval);
  137. gameEvents.giveResources(h->getOwner(), -mission.resources);
  138. }
  139. void CQuest::addTextReplacements(const IGameInfoCallback * cb, MetaString & text, std::vector<Component> & components) const
  140. {
  141. if(mission.heroLevel > 0)
  142. text.replaceNumber(mission.heroLevel);
  143. if(mission.heroExperience > 0)
  144. text.replaceNumber(mission.heroExperience);
  145. { //primary skills
  146. MetaString loot;
  147. for(int i = 0; i < 4; ++i)
  148. {
  149. if(mission.primary[i])
  150. {
  151. loot.appendRawString("%d %s");
  152. loot.replaceNumber(mission.primary[i]);
  153. loot.replaceRawString(LIBRARY->generaltexth->primarySkillNames[i]);
  154. }
  155. }
  156. for(auto & skill : mission.secondary)
  157. {
  158. loot.appendTextID(LIBRARY->skillh->getById(skill.first)->getNameTextID());
  159. }
  160. for(auto & spell : mission.spells)
  161. {
  162. loot.appendTextID(LIBRARY->spellh->getById(spell)->getNameTextID());
  163. }
  164. if(!loot.empty())
  165. text.replaceRawString(loot.buildList());
  166. }
  167. if(killTarget != ObjectInstanceID::NONE && !heroName.empty())
  168. {
  169. components.emplace_back(ComponentType::HERO_PORTRAIT, heroPortrait);
  170. addKillTargetReplacements(text);
  171. }
  172. if(killTarget != ObjectInstanceID::NONE && stackToKill != CreatureID::NONE)
  173. {
  174. components.emplace_back(ComponentType::CREATURE, stackToKill);
  175. addKillTargetReplacements(text);
  176. }
  177. if(!mission.heroes.empty())
  178. text.replaceRawString(LIBRARY->heroh->getById(mission.heroes.front())->getNameTranslated());
  179. if(!mission.artifacts.empty())
  180. {
  181. MetaString loot;
  182. for(const auto & elem : mission.artifacts)
  183. {
  184. loot.appendRawString("%s");
  185. loot.replaceName(elem);
  186. }
  187. text.replaceRawString(loot.buildList());
  188. }
  189. if(!mission.creatures.empty())
  190. {
  191. MetaString loot;
  192. for(const auto & elem : mission.creatures)
  193. {
  194. loot.appendRawString("%s");
  195. loot.replaceName(elem);
  196. }
  197. text.replaceRawString(loot.buildList());
  198. }
  199. if(mission.resources.nonZero())
  200. {
  201. MetaString loot;
  202. for(auto i : LIBRARY->resourceTypeHandler->getAllObjects())
  203. {
  204. if(mission.resources[i])
  205. {
  206. loot.appendRawString("%d %s");
  207. loot.replaceNumber(mission.resources[i]);
  208. loot.replaceName(i);
  209. }
  210. }
  211. text.replaceRawString(loot.buildList());
  212. }
  213. if(!mission.players.empty())
  214. {
  215. MetaString loot;
  216. for(auto & p : mission.players)
  217. loot.appendName(p);
  218. text.replaceRawString(loot.buildList());
  219. }
  220. if(lastDay >= 0)
  221. text.replaceNumber(lastDay - cb->getDate(Date::DAY));
  222. }
  223. void CQuest::getVisitText(const IGameInfoCallback * cb, MetaString &iwText, std::vector<Component> &components, bool firstVisit, const CGHeroInstance * h) const
  224. {
  225. bool failRequirements = (h ? !checkQuest(h) : true);
  226. mission.loadComponents(components, h);
  227. if(firstVisit)
  228. iwText.appendRawString(firstVisitText.toString());
  229. else if(failRequirements)
  230. iwText.appendRawString(nextVisitText.toString());
  231. if(lastDay >= 0)
  232. iwText.appendTextID(TextIdentifier("core", "seerhut", "time", textOption).get());
  233. addTextReplacements(cb, iwText, components);
  234. }
  235. void CQuest::getRolloverText(const IGameInfoCallback * cb, MetaString &ms, bool onHover) const
  236. {
  237. if(onHover)
  238. ms.appendRawString("\n\n");
  239. std::string questState = missionState(onHover ? 3 : 4);
  240. ms.appendTextID(TextIdentifier("core", "seerhut", "quest", questName, questState, textOption).get());
  241. std::vector<Component> components;
  242. addTextReplacements(cb, ms, components);
  243. }
  244. void CQuest::getCompletionText(const IGameInfoCallback * cb, MetaString &iwText) const
  245. {
  246. iwText.appendRawString(completedText.toString());
  247. std::vector<Component> components;
  248. addTextReplacements(cb, iwText, components);
  249. }
  250. void CQuest::defineQuestName()
  251. {
  252. //standard quests
  253. questName = CQuest::missionName(EQuestMission::NONE);
  254. if(mission.heroLevel > 0) questName = CQuest::missionName(EQuestMission::LEVEL);
  255. for(auto & s : mission.primary) if(s) questName = CQuest::missionName(EQuestMission::PRIMARY_SKILL);
  256. if(killTarget != ObjectInstanceID::NONE && !heroName.empty()) questName = CQuest::missionName(EQuestMission::KILL_HERO);
  257. if(killTarget != ObjectInstanceID::NONE && stackToKill != CreatureID::NONE) questName = CQuest::missionName(EQuestMission::KILL_CREATURE);
  258. if(!mission.artifacts.empty()) questName = CQuest::missionName(EQuestMission::ARTIFACT);
  259. if(!mission.creatures.empty()) questName = CQuest::missionName(EQuestMission::ARMY);
  260. if(mission.resources.nonZero()) questName = CQuest::missionName(EQuestMission::RESOURCES);
  261. if(!mission.heroes.empty()) questName = CQuest::missionName(EQuestMission::HERO);
  262. if(!mission.players.empty()) questName = CQuest::missionName(EQuestMission::PLAYER);
  263. if(mission.daysPassed > 0) questName = CQuest::missionName(EQuestMission::HOTA_REACH_DATE);
  264. if(!mission.heroClasses.empty()) questName = CQuest::missionName(EQuestMission::HOTA_HERO_CLASS);
  265. }
  266. void CQuest::addKillTargetReplacements(MetaString &out) const
  267. {
  268. if(!heroName.empty())
  269. out.replaceRawString(heroName);
  270. if(stackToKill != CreatureID::NONE)
  271. {
  272. out.replaceNamePlural(stackToKill);
  273. out.replaceRawString(LIBRARY->generaltexth->arraytxt[147+stackDirection]);
  274. }
  275. }
  276. void CQuest::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName)
  277. {
  278. auto q = handler.enterStruct(fieldName);
  279. handler.serializeStruct("firstVisitText", firstVisitText);
  280. handler.serializeStruct("nextVisitText", nextVisitText);
  281. handler.serializeStruct("completedText", completedText);
  282. handler.serializeBool("repeatedQuest", repeatedQuest, false);
  283. if(!handler.saving)
  284. {
  285. isCustomFirst = !firstVisitText.empty();
  286. isCustomNext = !nextVisitText.empty();
  287. isCustomComplete = !completedText.empty();
  288. }
  289. handler.serializeInt("timeLimit", lastDay, -1);
  290. handler.serializeStruct("limiter", mission);
  291. handler.serializeInstance("killTarget", killTarget, ObjectInstanceID::NONE);
  292. if(!handler.saving) //compatibility with legacy vmaps
  293. {
  294. std::string missionType = "None";
  295. handler.serializeString("missionType", missionType);
  296. if(missionType == "None")
  297. return;
  298. if(missionType == "Level")
  299. handler.serializeInt("heroLevel", mission.heroLevel);
  300. if(missionType == "PrimaryStat")
  301. {
  302. auto primarySkills = handler.enterStruct("primarySkills");
  303. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  304. handler.serializeInt(NPrimarySkill::names[i], mission.primary[i], 0);
  305. }
  306. if(missionType == "Artifact")
  307. handler.serializeIdArray<ArtifactID>("artifacts", mission.artifacts);
  308. if(missionType == "Army")
  309. {
  310. auto a = handler.enterArray("creatures");
  311. a.serializeStruct(mission.creatures);
  312. }
  313. if(missionType == "Resources")
  314. {
  315. auto r = handler.enterStruct("resources");
  316. for(auto & idx : LIBRARY->resourceTypeHandler->getAllObjects())
  317. if(idx != GameResID::MITHRIL)
  318. handler.serializeInt(idx.toResource()->getJsonKey(), mission.resources[idx], 0);
  319. }
  320. if(missionType == "Hero")
  321. {
  322. HeroTypeID temp;
  323. handler.serializeId("hero", temp, HeroTypeID::NONE);
  324. mission.heroes.emplace_back(temp);
  325. }
  326. if(missionType == "Player")
  327. {
  328. PlayerColor temp;
  329. handler.serializeId("player", temp, PlayerColor::NEUTRAL);
  330. mission.players.emplace_back(temp);
  331. }
  332. }
  333. }
  334. IQuestObject::IQuestObject()
  335. :quest(std::make_shared<CQuest>())
  336. {}
  337. IQuestObject::~IQuestObject() = default;
  338. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  339. {
  340. return getQuest().checkQuest(h);
  341. }
  342. void CGSeerHut::getVisitText(MetaString &text, std::vector<Component> &components, bool FirstVisit, const CGHeroInstance * h) const
  343. {
  344. getQuest().getVisitText(cb, text, components, FirstVisit, h);
  345. }
  346. void CGSeerHut::setObjToKill()
  347. {
  348. if(getQuest().killTarget == ObjectInstanceID::NONE)
  349. return;
  350. if(getCreatureToKill(true))
  351. {
  352. getQuest().stackToKill = getCreatureToKill(false)->getCreatureID();
  353. assert(getQuest().stackToKill != CreatureID::NONE);
  354. getQuest().stackDirection = checkDirection();
  355. }
  356. else if(getHeroToKill(true))
  357. {
  358. getQuest().heroName = getHeroToKill(false)->getNameTranslated();
  359. getQuest().heroPortrait = getHeroToKill(false)->getPortraitSource();
  360. }
  361. }
  362. void CGSeerHut::init(vstd::RNG & rand)
  363. {
  364. auto names = LIBRARY->generaltexth->findStringsWithPrefix("core.seerhut.names");
  365. auto seerNameID = *RandomGeneratorUtil::nextItem(names, rand);
  366. seerName = LIBRARY->generaltexth->translate(seerNameID);
  367. getQuest().textOption = rand.nextInt(2);
  368. getQuest().completedOption = rand.nextInt(1, 3);
  369. getQuest().mission.hasExtraCreatures = !allowsFullArmyRemoval();
  370. configuration.canRefuse = true;
  371. configuration.visitMode = Rewardable::EVisitMode::VISIT_ONCE;
  372. configuration.selectMode = Rewardable::ESelectMode::SELECT_PLAYER;
  373. }
  374. void CGSeerHut::initObj(IGameRandomizer & gameRandomizer)
  375. {
  376. init(gameRandomizer.getDefault());
  377. CRewardableObject::initObj(gameRandomizer);
  378. setObjToKill();
  379. getQuest().defineQuestName();
  380. if(getQuest().mission == Rewardable::Limiter{} && getQuest().killTarget == ObjectInstanceID::NONE)
  381. getQuest().isCompleted = true;
  382. if(getQuest().questName == getQuest().missionName(EQuestMission::NONE))
  383. {
  384. getQuest().firstVisitText.appendTextID(TextIdentifier("core", "seerhut", "empty", getQuest().completedOption).get());
  385. }
  386. else
  387. {
  388. if(!getQuest().isCustomFirst)
  389. getQuest().firstVisitText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest().questName, getQuest().missionState(0), getQuest().textOption).get());
  390. if(!getQuest().isCustomNext)
  391. getQuest().nextVisitText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest().questName, getQuest().missionState(1), getQuest().textOption).get());
  392. if(!getQuest().isCustomComplete)
  393. getQuest().completedText.appendTextID(TextIdentifier("core", "seerhut", "quest", getQuest(). questName, getQuest().missionState(2), getQuest().textOption).get());
  394. }
  395. getQuest().getCompletionText(cb, configuration.onSelect);
  396. for(auto & i : configuration.info)
  397. getQuest().getCompletionText(cb, i.message);
  398. }
  399. void CGSeerHut::getRolloverText(MetaString &text, bool onHover) const
  400. {
  401. getQuest().getRolloverText(cb, text, onHover);
  402. if(!onHover)
  403. text.replaceRawString(seerName);
  404. }
  405. std::string CGSeerHut::getHoverText(PlayerColor player) const
  406. {
  407. std::string hoverName = getObjectName();
  408. if(ID == Obj::SEER_HUT && getQuest().activeForPlayers.count(player))
  409. {
  410. hoverName = LIBRARY->generaltexth->allTexts[347];
  411. boost::algorithm::replace_first(hoverName, "%s", seerName);
  412. }
  413. if(getQuest().activeForPlayers.count(player)
  414. && (getQuest().mission != Rewardable::Limiter{}
  415. || getQuest().killTarget != ObjectInstanceID::NONE)) //rollover when the quest is active
  416. {
  417. MetaString ms;
  418. getRolloverText (ms, true);
  419. hoverName += ms.toString();
  420. }
  421. return hoverName;
  422. }
  423. std::string CGSeerHut::getHoverText(const CGHeroInstance * hero) const
  424. {
  425. return getHoverText(hero->getOwner());
  426. }
  427. std::string CGSeerHut::getPopupText(PlayerColor player) const
  428. {
  429. return getHoverText(player);
  430. }
  431. std::string CGSeerHut::getPopupText(const CGHeroInstance * hero) const
  432. {
  433. return getHoverText(hero->getOwner());
  434. }
  435. std::vector<Component> CGSeerHut::getPopupComponents(PlayerColor player) const
  436. {
  437. std::vector<Component> result;
  438. if (getQuest().activeForPlayers.count(player))
  439. getQuest().mission.loadComponents(result, nullptr);
  440. return result;
  441. }
  442. std::vector<Component> CGSeerHut::getPopupComponents(const CGHeroInstance * hero) const
  443. {
  444. std::vector<Component> result;
  445. if (getQuest().activeForPlayers.count(hero->getOwner()))
  446. getQuest().mission.loadComponents(result, hero);
  447. return result;
  448. }
  449. void CGSeerHut::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  450. {
  451. switch(what)
  452. {
  453. case ObjProperty::SEERHUT_VISITED:
  454. {
  455. getQuest().activeForPlayers.emplace(identifier.as<PlayerColor>());
  456. break;
  457. }
  458. case ObjProperty::SEERHUT_COMPLETE:
  459. {
  460. getQuest().isCompleted = identifier.getNum();
  461. getQuest().activeForPlayers.clear();
  462. break;
  463. }
  464. }
  465. }
  466. void CGSeerHut::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  467. {
  468. CRewardableObject::newTurn(gameEvents, gameRandomizer);
  469. if(getQuest().lastDay >= 0 && getQuest().lastDay <= cb->getDate() - 1) //time is up
  470. {
  471. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, true);
  472. }
  473. }
  474. void CGSeerHut::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  475. {
  476. InfoWindow iw;
  477. iw.player = h->getOwner();
  478. if(!getQuest().isCompleted)
  479. {
  480. bool firstVisit = !getQuest().activeForPlayers.count(h->getOwner());
  481. bool failRequirements = !checkQuest(h);
  482. if(firstVisit)
  483. {
  484. gameEvents.setObjPropertyID(id, ObjProperty::SEERHUT_VISITED, h->getOwner());
  485. AddQuest aq;
  486. aq.quest = QuestInfo(id);
  487. aq.player = h->tempOwner;
  488. gameEvents.sendAndApply(aq); //TODO: merge with setObjProperty?
  489. }
  490. if(firstVisit || failRequirements)
  491. {
  492. getVisitText (iw.text, iw.components, firstVisit, h);
  493. gameEvents.showInfoDialog(&iw);
  494. }
  495. if(!failRequirements) // propose completion, also on first visit
  496. {
  497. CRewardableObject::onHeroVisit(gameEvents, h);
  498. return;
  499. }
  500. }
  501. else
  502. {
  503. iw.text.appendRawString(LIBRARY->generaltexth->seerEmpty[getQuest().completedOption]);
  504. if (ID == Obj::SEER_HUT)
  505. iw.text.replaceRawString(seerName);
  506. gameEvents.showInfoDialog(&iw);
  507. }
  508. }
  509. int CGSeerHut::checkDirection() const
  510. {
  511. int3 cord = getCreatureToKill(false)->visitablePos();
  512. if(static_cast<double>(cord.x) / static_cast<double>(cb->getMapSize().x) < 0.34) //north
  513. {
  514. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //northwest
  515. return 8;
  516. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //north
  517. return 1;
  518. else //northeast
  519. return 2;
  520. }
  521. else if(static_cast<double>(cord.x) / static_cast<double>(cb->getMapSize().x) < 0.67) //horizontal
  522. {
  523. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //west
  524. return 7;
  525. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //central
  526. return 9;
  527. else //east
  528. return 3;
  529. }
  530. else //south
  531. {
  532. if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.34) //southwest
  533. return 6;
  534. else if(static_cast<double>(cord.y) / static_cast<double>(cb->getMapSize().y) < 0.67) //south
  535. return 5;
  536. else //southeast
  537. return 4;
  538. }
  539. }
  540. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  541. {
  542. const CGObjectInstance *o = cb->getObj(getQuest().killTarget);
  543. if(allowNull && !o)
  544. return nullptr;
  545. return dynamic_cast<const CGHeroInstance *>(o);
  546. }
  547. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  548. {
  549. const CGObjectInstance *o = cb->getObj(getQuest().killTarget);
  550. if(allowNull && !o)
  551. return nullptr;
  552. return dynamic_cast<const CGCreature *>(o);
  553. }
  554. bool CGSeerHut::allowsFullArmyRemoval() const
  555. {
  556. bool seerGivesUnits = !configuration.info.empty() && !configuration.info.back().reward.creatures.empty();
  557. bool h3BugSettingEnabled = cb->getSettings().getBoolean(EGameSettings::MAP_OBJECTS_H3_BUG_QUEST_TAKES_ENTIRE_ARMY);
  558. return seerGivesUnits || h3BugSettingEnabled;
  559. }
  560. void CGSeerHut::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  561. {
  562. if(answer)
  563. {
  564. getQuest().completeQuest(gameEvents, hero, allowsFullArmyRemoval());
  565. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, !getQuest().repeatedQuest); //mission complete
  566. }
  567. CRewardableObject::blockingDialogAnswered(gameEvents, hero, answer);
  568. }
  569. void CGSeerHut::serializeJsonOptions(JsonSerializeFormat & handler)
  570. {
  571. //quest and reward
  572. CRewardableObject::serializeJsonOptions(handler);
  573. getQuest().serializeJson(handler, "quest");
  574. if(!handler.saving)
  575. {
  576. //backward compatibility for VCMI maps that use old SeerHut format
  577. auto s = handler.enterStruct("reward");
  578. const JsonNode & rewardsJson = handler.getCurrent();
  579. if (rewardsJson.Struct().empty())
  580. return;
  581. std::string fullIdentifier;
  582. std::string metaTypeName;
  583. std::string scope;
  584. std::string identifier;
  585. auto iter = rewardsJson.Struct().begin();
  586. fullIdentifier = iter->first;
  587. ModUtility::parseIdentifier(fullIdentifier, scope, metaTypeName, identifier);
  588. if(!std::set<std::string>{"resource", "primarySkill", "secondarySkill", "artifact", "spell", "creature", "experience", "mana", "morale", "luck"}.count(metaTypeName))
  589. return;
  590. int val = 0;
  591. handler.serializeInt(fullIdentifier, val);
  592. Rewardable::VisitInfo vinfo;
  593. auto & reward = vinfo.reward;
  594. if(metaTypeName == "experience")
  595. reward.heroExperience = val;
  596. if(metaTypeName == "mana")
  597. reward.manaDiff = val;
  598. if(metaTypeName == "morale")
  599. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(id)));
  600. if(metaTypeName == "luck")
  601. reward.heroBonuses.push_back(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(id)));
  602. if(metaTypeName == "resource")
  603. {
  604. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  605. reward.resources[rawId] = val;
  606. }
  607. if(metaTypeName == "primarySkill")
  608. {
  609. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  610. reward.primary.at(rawId) = val;
  611. }
  612. if(metaTypeName == "secondarySkill")
  613. {
  614. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  615. reward.secondary[rawId] = val;
  616. }
  617. if(metaTypeName == "artifact")
  618. {
  619. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  620. reward.grantedArtifacts.push_back(rawId);
  621. }
  622. if(metaTypeName == "spell")
  623. {
  624. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  625. reward.spells.push_back(rawId);
  626. }
  627. if(metaTypeName == "creature")
  628. {
  629. auto rawId = *LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), fullIdentifier, false);
  630. reward.creatures.emplace_back(rawId, val);
  631. }
  632. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  633. configuration.info.push_back(vinfo);
  634. }
  635. }
  636. void CGQuestGuard::init(vstd::RNG & rand)
  637. {
  638. blockVisit = true;
  639. getQuest().textOption = rand.nextInt(3, 5);
  640. getQuest().completedOption = rand.nextInt(4, 5);
  641. getQuest().mission.hasExtraCreatures = !allowsFullArmyRemoval();
  642. configuration.info.push_back({});
  643. configuration.info.back().visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  644. configuration.info.back().reward.removeObject = subID.getNum() == 0 ? true : false;
  645. configuration.canRefuse = true;
  646. }
  647. void CGQuestGuard::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  648. {
  649. if(!getQuest().isCompleted)
  650. CGSeerHut::onHeroVisit(gameEvents, h);
  651. else
  652. gameEvents.setObjPropertyValue(id, ObjProperty::SEERHUT_COMPLETE, false);
  653. }
  654. bool CGQuestGuard::passableFor(PlayerColor color) const
  655. {
  656. return getQuest().isCompleted;
  657. }
  658. void CGQuestGuard::serializeJsonOptions(JsonSerializeFormat & handler)
  659. {
  660. //quest only, do not call base class
  661. getQuest().serializeJson(handler, "quest");
  662. }
  663. bool CGKeys::wasMyColorVisited(const PlayerColor & player) const
  664. {
  665. return cb->getPlayerState(player)->visitedObjectsGlobal.count({Obj::KEYMASTER, subID}) != 0;
  666. }
  667. std::string CGKeys::getHoverText(PlayerColor player) const
  668. {
  669. return getObjectName() + "\n" + visitedTxt(wasMyColorVisited(player));
  670. }
  671. std::string CGKeys::getObjectName() const
  672. {
  673. return LIBRARY->generaltexth->tentColors[subID.getNum()] + " " + CGObjectInstance::getObjectName();
  674. }
  675. std::string CGKeys::getObjectDescription(PlayerColor player) const
  676. {
  677. return visitedTxt(wasMyColorVisited(player));
  678. }
  679. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  680. {
  681. return wasMyColorVisited (player);
  682. }
  683. void CGKeymasterTent::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  684. {
  685. int txt_id;
  686. if (!wasMyColorVisited (h->getOwner()) )
  687. {
  688. ChangeObjectVisitors cow;
  689. cow.mode = ChangeObjectVisitors::VISITOR_ADD_PLAYER;
  690. cow.hero = h->id;
  691. cow.object = id;
  692. gameEvents.sendAndApply(cow);
  693. txt_id=19;
  694. }
  695. else
  696. txt_id=20;
  697. h->showInfoDialog(gameEvents, txt_id);
  698. }
  699. void CGBorderGuard::initObj(IGameRandomizer & gameRandomizer)
  700. {
  701. blockVisit = true;
  702. }
  703. void CGBorderGuard::getVisitText(MetaString &text, std::vector<Component> &components, bool FirstVisit, const CGHeroInstance * h) const
  704. {
  705. text.appendLocalString(EMetaText::ADVOB_TXT, 18);
  706. }
  707. void CGBorderGuard::getRolloverText(MetaString &text, bool onHover) const
  708. {
  709. if (!onHover)
  710. {
  711. text.appendRawString(LIBRARY->generaltexth->tentColors[subID.getNum()]);
  712. text.appendRawString(" ");
  713. text.appendRawString(LIBRARY->objtypeh->getObjectName(Obj::KEYMASTER, subID));
  714. }
  715. }
  716. bool CGBorderGuard::checkQuest(const CGHeroInstance * h) const
  717. {
  718. return wasMyColorVisited (h->tempOwner);
  719. }
  720. void CGBorderGuard::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  721. {
  722. if (wasMyColorVisited (h->getOwner()) )
  723. {
  724. BlockingDialog bd (true, false);
  725. bd.player = h->getOwner();
  726. bd.text.appendLocalString (EMetaText::ADVOB_TXT, 17);
  727. gameEvents.showBlockingDialog (this, &bd);
  728. }
  729. else
  730. {
  731. h->showInfoDialog(gameEvents, 18);
  732. AddQuest aq;
  733. aq.quest = QuestInfo(id);
  734. aq.player = h->tempOwner;
  735. gameEvents.sendAndApply(aq);
  736. //TODO: add this quest only once OR check for multiple instances later
  737. }
  738. }
  739. void CGBorderGuard::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  740. {
  741. if (answer)
  742. gameEvents.removeObject(this, hero->getOwner());
  743. }
  744. void CGBorderGate::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const //TODO: passability
  745. {
  746. if (!wasMyColorVisited (h->getOwner()) )
  747. {
  748. h->showInfoDialog(gameEvents, 18);
  749. AddQuest aq;
  750. aq.quest = QuestInfo(id);
  751. aq.player = h->tempOwner;
  752. gameEvents.sendAndApply(aq);
  753. }
  754. }
  755. bool CGBorderGate::passableFor(PlayerColor color) const
  756. {
  757. return wasMyColorVisited(color);
  758. }
  759. VCMI_LIB_NAMESPACE_END