MiscObjects.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. /*
  2. * MiscObjects.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 "MiscObjects.h"
  12. #include "../ArtifactUtils.h"
  13. #include "../bonuses/Propagators.h"
  14. #include "../constants/StringConstants.h"
  15. #include "../CConfigHandler.h"
  16. #include "../texts/CGeneralTextHandler.h"
  17. #include "../CSoundBase.h"
  18. #include "../CSkillHandler.h"
  19. #include "../spells/CSpellHandler.h"
  20. #include "../IGameCallback.h"
  21. #include "../gameState/CGameState.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../StartInfo.h"
  25. #include "../serializer/JsonSerializeFormat.h"
  26. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  27. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  28. #include "../mapObjects/CGHeroInstance.h"
  29. #include "../modding/ModScope.h"
  30. #include "../networkPacks/PacksForClient.h"
  31. #include "../networkPacks/PacksForClientBattle.h"
  32. #include "../networkPacks/StackLocation.h"
  33. #include "../lib/gameState/UpgradeInfo.h"
  34. #include <vstd/RNG.h>
  35. VCMI_LIB_NAMESPACE_BEGIN
  36. ///helpers
  37. static std::string visitedTxt(const bool visited)
  38. {
  39. int id = visited ? 352 : 353;
  40. return LIBRARY->generaltexth->allTexts[id];
  41. }
  42. void CTeamVisited::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  43. {
  44. if(what == ObjProperty::VISITED)
  45. players.insert(identifier.as<PlayerColor>());
  46. }
  47. bool CTeamVisited::wasVisited(PlayerColor player) const
  48. {
  49. return wasVisited(cb->getPlayerState(player)->team);
  50. }
  51. bool CTeamVisited::wasVisited(const CGHeroInstance * h) const
  52. {
  53. return wasVisited(h->tempOwner);
  54. }
  55. bool CTeamVisited::wasVisited(const TeamID & team) const
  56. {
  57. for(const auto & i : players)
  58. {
  59. if(cb->getPlayerState(i)->team == team)
  60. return true;
  61. }
  62. return false;
  63. }
  64. //CGMine
  65. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  66. {
  67. auto relations = cb->gameState().getPlayerRelations(h->tempOwner, tempOwner);
  68. if(relations == PlayerRelations::SAME_PLAYER) //we're visiting our mine
  69. {
  70. cb->showGarrisonDialog(id,h->id,true);
  71. return;
  72. }
  73. else if (relations == PlayerRelations::ALLIES)//ally
  74. return;
  75. if(stacksCount()) //Mine is guarded
  76. {
  77. BlockingDialog ynd(true,false);
  78. ynd.player = h->tempOwner;
  79. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, isAbandoned() ? 84 : 187);
  80. cb->showBlockingDialog(this, &ynd);
  81. return;
  82. }
  83. flagMine(h->tempOwner);
  84. }
  85. void CGMine::initObj(vstd::RNG & rand)
  86. {
  87. if(isAbandoned())
  88. {
  89. //set guardians
  90. int howManyTroglodytes = rand.nextInt(100, 199);
  91. auto troglodytes = std::make_unique<CStackInstance>(cb, CreatureID::TROGLODYTES, howManyTroglodytes);
  92. putStack(SlotID(0), std::move(troglodytes));
  93. assert(!abandonedMineResources.empty());
  94. if (!abandonedMineResources.empty())
  95. {
  96. producedResource = *RandomGeneratorUtil::nextItem(abandonedMineResources, rand);
  97. }
  98. else
  99. {
  100. logGlobal->error("Abandoned mine at (%s) has no valid resource candidates!", anchorPos().toString());
  101. producedResource = GameResID::GOLD;
  102. }
  103. }
  104. else
  105. {
  106. producedResource = GameResID(getObjTypeIndex().getNum());
  107. }
  108. producedQuantity = defaultResProduction();
  109. }
  110. bool CGMine::isAbandoned() const
  111. {
  112. return subID.getNum() >= 7;
  113. }
  114. const IOwnableObject * CGMine::asOwnable() const
  115. {
  116. return this;
  117. }
  118. std::vector<CreatureID> CGMine::providedCreatures() const
  119. {
  120. return {};
  121. }
  122. ResourceSet CGMine::dailyIncome() const
  123. {
  124. ResourceSet result;
  125. result[producedResource] += defaultResProduction();
  126. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  127. result.applyHandicap(playerSettings->handicap.percentIncome);
  128. return result;
  129. }
  130. std::string CGMine::getObjectName() const
  131. {
  132. return LIBRARY->generaltexth->translate("core.minename", getObjTypeIndex());
  133. }
  134. std::string CGMine::getHoverText(PlayerColor player) const
  135. {
  136. std::string hoverName = CArmedInstance::getHoverText(player);
  137. if (tempOwner != PlayerColor::NEUTRAL)
  138. hoverName += "\n(" + LIBRARY->generaltexth->restypes[producedResource.getNum()] + ")";
  139. if(stacksCount())
  140. {
  141. hoverName += "\n";
  142. hoverName += LIBRARY->generaltexth->allTexts[202]; //Guarded by
  143. hoverName += " ";
  144. hoverName += getArmyDescription();
  145. }
  146. return hoverName;
  147. }
  148. void CGMine::flagMine(const PlayerColor & player) const
  149. {
  150. assert(tempOwner != player);
  151. cb->setOwner(this, player); //not ours? flag it!
  152. InfoWindow iw;
  153. iw.type = EInfoWindowMode::AUTO;
  154. iw.text.appendTextID(TextIdentifier("core.mineevnt", producedResource.getNum()).get()); //not use subID, abandoned mines uses default mine texts
  155. iw.player = player;
  156. iw.components.emplace_back(ComponentType::RESOURCE_PER_DAY, producedResource, getProducedQuantity());
  157. cb->showInfoDialog(&iw);
  158. }
  159. ui32 CGMine::defaultResProduction() const
  160. {
  161. switch(producedResource.toEnum())
  162. {
  163. case EGameResID::WOOD:
  164. case EGameResID::ORE:
  165. return 2;
  166. case EGameResID::GOLD:
  167. return 1000;
  168. default:
  169. return 1;
  170. }
  171. }
  172. ui32 CGMine::getProducedQuantity() const
  173. {
  174. auto * playerSettings = cb->getPlayerSettings(getOwner());
  175. // always round up income - we don't want mines to always produce zero if handicap in use
  176. return vstd::divideAndCeil(producedQuantity * playerSettings->handicap.percentIncome, 100);
  177. }
  178. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  179. {
  180. if(result.winner == BattleSide::ATTACKER) //attacker won
  181. {
  182. if(isAbandoned())
  183. {
  184. hero->showInfoDialog(85);
  185. }
  186. flagMine(hero->tempOwner);
  187. }
  188. }
  189. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  190. {
  191. if(answer)
  192. cb->startBattle(hero, this);
  193. }
  194. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  195. {
  196. CArmedInstance::serializeJsonOptions(handler);
  197. serializeJsonOwner(handler);
  198. if(isAbandoned())
  199. {
  200. if(handler.saving)
  201. {
  202. JsonNode node;
  203. for(const auto & resID : abandonedMineResources)
  204. node.Vector().emplace_back(GameConstants::RESOURCE_NAMES[resID.getNum()]);
  205. handler.serializeRaw("possibleResources", node, std::nullopt);
  206. }
  207. else
  208. {
  209. auto guard = handler.enterArray("possibleResources");
  210. const JsonNode & node = handler.getCurrent();
  211. auto names = node.convertTo<std::vector<std::string>>();
  212. for(const std::string & s : names)
  213. {
  214. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  215. if(raw_res < 0)
  216. logGlobal->error("Invalid resource name: %s", s);
  217. else
  218. abandonedMineResources.emplace(raw_res);
  219. }
  220. }
  221. }
  222. }
  223. bool CGTeleport::isEntrance() const
  224. {
  225. return type == BOTH || type == ENTRANCE;
  226. }
  227. bool CGTeleport::isExit() const
  228. {
  229. return type == BOTH || type == EXIT;
  230. }
  231. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  232. {
  233. return vstd::contains(getAllEntrances(), id);
  234. }
  235. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  236. {
  237. return vstd::contains(getAllExits(), id);
  238. }
  239. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  240. {
  241. auto ret = cb->getTeleportChannelEntrances(channel);
  242. if(excludeCurrent)
  243. vstd::erase_if_present(ret, id);
  244. return ret;
  245. }
  246. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  247. {
  248. auto ret = cb->getTeleportChannelExits(channel);
  249. if(excludeCurrent)
  250. vstd::erase_if_present(ret, id);
  251. return ret;
  252. }
  253. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  254. {
  255. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  256. if(!passableExits.empty())
  257. return *RandomGeneratorUtil::nextItem(passableExits, cb->gameState().getRandomGenerator());
  258. return ObjectInstanceID();
  259. }
  260. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  261. {
  262. return dynamic_cast<const CGTeleport *>(obj) != nullptr;
  263. }
  264. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  265. {
  266. return src && dst && src->isChannelExit(dst->id);
  267. }
  268. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  269. {
  270. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  271. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  272. return isConnected(srcObj, dstObj);
  273. }
  274. bool CGTeleport::isExitPassable(const CGameState & gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  275. {
  276. ObjectInstanceID topObjectID = gs.getMap().getTile(obj->visitablePos()).topVisitableObj();
  277. const CGObjectInstance * topObject = gs.getObjInstance(topObjectID);
  278. if(topObject->ID == Obj::HERO)
  279. {
  280. if(h->id == topObject->id) // Just to be sure it's won't happen.
  281. return false;
  282. // Check if it's friendly hero or not
  283. if(gs.getPlayerRelations(h->tempOwner, topObject->tempOwner) != PlayerRelations::ENEMIES)
  284. {
  285. // Exchange between heroes only possible via subterranean gates
  286. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  287. return false;
  288. }
  289. }
  290. return true;
  291. }
  292. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(const CGameState & gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  293. {
  294. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  295. {
  296. return !isExitPassable(gs, h, gs.getObj(exit));
  297. });
  298. return exits;
  299. }
  300. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  301. {
  302. std::shared_ptr<TeleportChannel> tc;
  303. if(channelsList.find(obj->channel) == channelsList.end())
  304. {
  305. tc = std::make_shared<TeleportChannel>();
  306. channelsList.insert(std::make_pair(obj->channel, tc));
  307. }
  308. else
  309. tc = channelsList[obj->channel];
  310. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  311. tc->entrances.push_back(obj->id);
  312. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  313. tc->exits.push_back(obj->id);
  314. if(!tc->entrances.empty() && !tc->exits.empty()
  315. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  316. {
  317. tc->passability = TeleportChannel::PASSABLE;
  318. }
  319. }
  320. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, MapObjectSubID SubID) const
  321. {
  322. for(auto teleportObj : cb->gameState().getMap().getObjects<CGMonolith>())
  323. {
  324. if(vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  325. return teleportObj->channel;
  326. }
  327. return TeleportChannelID();
  328. }
  329. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  330. {
  331. TeleportDialog td(h->id, channel);
  332. if(isEntrance())
  333. {
  334. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  335. {
  336. auto exits = cb->getTeleportChannelExits(channel);
  337. for(const auto & exit : exits)
  338. {
  339. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  340. }
  341. }
  342. if(cb->isTeleportChannelImpassable(channel))
  343. {
  344. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), anchorPos().toString());
  345. td.impassable = true;
  346. }
  347. else if(getRandomExit(h) == ObjectInstanceID())
  348. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), anchorPos().toString());
  349. }
  350. else
  351. h->showInfoDialog(70);
  352. cb->showTeleportDialog(&td);
  353. }
  354. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  355. {
  356. int3 dPos;
  357. auto randomExit = getRandomExit(hero);
  358. auto realExits = getAllExits(true);
  359. if(!isEntrance() // Do nothing if hero visited exit only object
  360. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  361. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  362. {
  363. return;
  364. }
  365. else if(vstd::isValidIndex(exits, answer))
  366. dPos = exits[answer].second;
  367. else
  368. dPos = cb->getObj(randomExit)->visitablePos();
  369. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  370. }
  371. void CGMonolith::initObj(vstd::RNG & rand)
  372. {
  373. std::vector<Obj> IDs;
  374. IDs.push_back(ID);
  375. switch(ID.toEnum())
  376. {
  377. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  378. type = ENTRANCE;
  379. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  380. break;
  381. case Obj::MONOLITH_ONE_WAY_EXIT:
  382. type = EXIT;
  383. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  384. break;
  385. case Obj::MONOLITH_TWO_WAY:
  386. default:
  387. type = BOTH;
  388. break;
  389. }
  390. channel = findMeChannel(IDs, subID);
  391. if(channel == TeleportChannelID())
  392. channel = TeleportChannelID(static_cast<si32>(cb->gameState().getMap().teleportChannels.size()));
  393. addToChannel(cb->gameState().getMap().teleportChannels, this);
  394. }
  395. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  396. {
  397. TeleportDialog td(h->id, channel);
  398. if(cb->isTeleportChannelImpassable(channel))
  399. {
  400. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  401. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), anchorPos().toString());
  402. td.impassable = true;
  403. }
  404. else
  405. {
  406. auto exit = getRandomExit(h);
  407. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  408. }
  409. cb->showTeleportDialog(&td);
  410. }
  411. void CGSubterraneanGate::initObj(vstd::RNG & rand)
  412. {
  413. type = BOTH;
  414. }
  415. void CGSubterraneanGate::postInit(IGameCallback * cb) //matches subterranean gates into pairs
  416. {
  417. //split on underground and surface gates
  418. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  419. for(auto gate : cb->gameState().getMap().getObjects<CGSubterraneanGate>())
  420. {
  421. gatesSplit[gate->visitablePos().z].push_back(gate);
  422. }
  423. //sort by position
  424. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  425. {
  426. return a->visitablePos() < b->visitablePos();
  427. });
  428. auto assignToChannel = [&](CGSubterraneanGate * obj)
  429. {
  430. if(obj->channel == TeleportChannelID())
  431. { // if object not linked to channel then create new channel
  432. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState().getMap().teleportChannels.size()));
  433. addToChannel(cb->gameState().getMap().teleportChannels, obj);
  434. }
  435. };
  436. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  437. {
  438. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  439. //find nearest underground exit
  440. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  441. for(int j = 0; j < gatesSplit[1].size(); j++)
  442. {
  443. CGSubterraneanGate *checked = gatesSplit[1][j];
  444. if(checked->channel != TeleportChannelID())
  445. continue;
  446. si32 hlp = checked->visitablePos().dist2dSQ(objCurrent->visitablePos());
  447. if(hlp < best.second)
  448. {
  449. best.first = j;
  450. best.second = hlp;
  451. }
  452. }
  453. assignToChannel(objCurrent);
  454. if(best.first >= 0) //found pair
  455. {
  456. gatesSplit[1][best.first]->channel = objCurrent->channel;
  457. addToChannel(cb->gameState().getMap().teleportChannels, gatesSplit[1][best.first]);
  458. }
  459. }
  460. // we should assign empty channels to underground gates if they don't have matching overground gates
  461. for(auto & i : gatesSplit[1])
  462. assignToChannel(i);
  463. }
  464. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  465. {
  466. TeleportDialog td(h->id, channel);
  467. if(cb->isTeleportChannelImpassable(channel))
  468. {
  469. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), anchorPos().toString());
  470. td.impassable = true;
  471. }
  472. else if(getRandomExit(h) == ObjectInstanceID())
  473. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), anchorPos().toString());
  474. if(!isProtected(h))
  475. {
  476. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  477. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  478. {
  479. if(h->getPower(targetstack) > h->getPower(i->first))
  480. targetstack = (i->first);
  481. }
  482. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  483. vstd::amax(countToTake, 1);
  484. InfoWindow iw;
  485. iw.type = EInfoWindowMode::AUTO;
  486. iw.player = h->tempOwner;
  487. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 168);
  488. iw.components.emplace_back(ComponentType::CREATURE, h->getCreature(targetstack)->getId(), -countToTake);
  489. cb->showInfoDialog(&iw);
  490. cb->changeStackCount(StackLocation(h->id, targetstack), -countToTake);
  491. }
  492. else
  493. {
  494. auto exits = getAllExits();
  495. for(const auto & exit : exits)
  496. {
  497. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  498. for(const auto & bPos : blockedPosList)
  499. td.exits.push_back(std::make_pair(exit, bPos));
  500. }
  501. }
  502. cb->showTeleportDialog(&td);
  503. }
  504. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  505. {
  506. int3 dPos;
  507. auto realExits = getAllExits();
  508. if(exits.empty() && realExits.empty())
  509. return;
  510. else if(vstd::isValidIndex(exits, answer))
  511. dPos = exits[answer].second;
  512. else
  513. {
  514. auto exit = getRandomExit(hero);
  515. if(exit == ObjectInstanceID())
  516. return;
  517. const auto * obj = cb->getObj(exit);
  518. std::set<int3> tiles = obj->getBlockedPos();
  519. dPos = *RandomGeneratorUtil::nextItem(tiles, cb->gameState().getRandomGenerator());
  520. }
  521. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  522. }
  523. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  524. {
  525. return h->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION)
  526. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1)
  527. || (h->stacksCount() == 0 && h->getCommander() && h->getCommander()->alive);
  528. }
  529. const CArtifactInstance * CGArtifact::getArtifactInstance() const
  530. {
  531. return cb->getArtInstance(storedArtifact);
  532. }
  533. ArtifactID CGArtifact::getArtifactType() const
  534. {
  535. if(ID == Obj::SPELL_SCROLL)
  536. return ArtifactID::SPELL_SCROLL;
  537. else
  538. return getObjTypeIndex().getNum();
  539. }
  540. void CGArtifact::pickRandomObject(vstd::RNG & rand)
  541. {
  542. switch(ID.toEnum())
  543. {
  544. case MapObjectID::RANDOM_ART:
  545. subID = cb->gameState().pickRandomArtifact(rand, CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC);
  546. break;
  547. case MapObjectID::RANDOM_TREASURE_ART:
  548. subID = cb->gameState().pickRandomArtifact(rand, CArtifact::ART_TREASURE);
  549. break;
  550. case MapObjectID::RANDOM_MINOR_ART:
  551. subID = cb->gameState().pickRandomArtifact(rand, CArtifact::ART_MINOR);
  552. break;
  553. case MapObjectID::RANDOM_MAJOR_ART:
  554. subID = cb->gameState().pickRandomArtifact(rand, CArtifact::ART_MAJOR);
  555. break;
  556. case MapObjectID::RANDOM_RELIC_ART:
  557. subID = cb->gameState().pickRandomArtifact(rand, CArtifact::ART_RELIC);
  558. break;
  559. }
  560. if (ID != MapObjectID::SPELL_SCROLL && ID != MapObjectID::ARTIFACT)
  561. {
  562. ID = MapObjectID::ARTIFACT;
  563. setType(ID, subID);
  564. }
  565. else if (ID != MapObjectID::SPELL_SCROLL)
  566. ID = MapObjectID::ARTIFACT;
  567. }
  568. void CGArtifact::setArtifactInstance(const CArtifactInstance * instance)
  569. {
  570. storedArtifact = instance->getId();
  571. }
  572. void CGArtifact::initObj(vstd::RNG & rand)
  573. {
  574. blockVisit = true;
  575. if(ID == Obj::ARTIFACT)
  576. {
  577. assert(getArtifactType().hasValue());
  578. if (!storedArtifact.hasValue())
  579. setArtifactInstance(cb->gameState().createArtifact(getArtifactType()));
  580. }
  581. if(ID == Obj::SPELL_SCROLL)
  582. subID = 1;
  583. assert(getArtifactInstance()->getType());
  584. assert(!getArtifactInstance()->getParentNodes().empty());
  585. }
  586. std::string CGArtifact::getObjectName() const
  587. {
  588. return getArtifactType().toEntity(LIBRARY)->getNameTranslated();
  589. }
  590. std::string CGArtifact::getPopupText(PlayerColor player) const
  591. {
  592. if (settings["general"]["enableUiEnhancements"].Bool())
  593. {
  594. std::string description = getArtifactType().toEntity(LIBRARY)->getDescriptionTranslated();
  595. if (getArtifactType() == ArtifactID::SPELL_SCROLL)
  596. ArtifactUtils::insertScrrollSpellName(description, SpellID::NONE); // erase text placeholder
  597. return description;
  598. }
  599. else
  600. return getObjectName();
  601. }
  602. std::string CGArtifact::getPopupText(const CGHeroInstance * hero) const
  603. {
  604. return getPopupText(hero->getOwner());
  605. }
  606. std::vector<Component> CGArtifact::getPopupComponents(PlayerColor player) const
  607. {
  608. return {
  609. Component(ComponentType::ARTIFACT, getArtifactType())
  610. };
  611. }
  612. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  613. {
  614. if(!stacksCount())
  615. {
  616. InfoWindow iw;
  617. iw.type = EInfoWindowMode::AUTO;
  618. iw.player = h->tempOwner;
  619. if(getArtifactInstance()->getType()->canBePutAt(h))
  620. {
  621. switch (ID.toEnum())
  622. {
  623. case Obj::ARTIFACT:
  624. {
  625. iw.components.emplace_back(ComponentType::ARTIFACT, getArtifactType());
  626. if(!message.empty())
  627. iw.text = message;
  628. else
  629. iw.text.appendTextID(getArtifactType().toArtifact()->getEventTextID());
  630. }
  631. break;
  632. case Obj::SPELL_SCROLL:
  633. {
  634. SpellID spell = getArtifactInstance()->getScrollSpellID();
  635. iw.components.emplace_back(ComponentType::SPELL, spell);
  636. if(!message.empty())
  637. iw.text = message;
  638. else
  639. {
  640. iw.text.appendLocalString(EMetaText::ADVOB_TXT,135);
  641. iw.text.replaceName(spell);
  642. }
  643. }
  644. break;
  645. }
  646. }
  647. else
  648. {
  649. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 2);
  650. }
  651. cb->showInfoDialog(&iw);
  652. pick(h);
  653. }
  654. else
  655. {
  656. switch(ID.toEnum())
  657. {
  658. case Obj::ARTIFACT:
  659. {
  660. BlockingDialog ynd(true,false);
  661. ynd.player = h->getOwner();
  662. if(!message.empty())
  663. ynd.text = message;
  664. else
  665. {
  666. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  667. ynd.text.appendLocalString(EMetaText::GENERAL_TXT, 420);
  668. ynd.text.replaceRawString("");
  669. ynd.text.replaceRawString(getArmyDescription());
  670. ynd.text.replaceLocalString(EMetaText::GENERAL_TXT, 43); // creatures
  671. }
  672. cb->showBlockingDialog(this, &ynd);
  673. }
  674. break;
  675. case Obj::SPELL_SCROLL:
  676. {
  677. if(!message.empty())
  678. {
  679. BlockingDialog ynd(true,false);
  680. ynd.player = h->getOwner();
  681. ynd.text = message;
  682. cb->showBlockingDialog(this, &ynd);
  683. }
  684. else
  685. blockingDialogAnswered(h, true);
  686. }
  687. break;
  688. }
  689. }
  690. }
  691. void CGArtifact::pick(const CGHeroInstance * h) const
  692. {
  693. if(cb->putArtifact(ArtifactLocation(h->id, ArtifactPosition::FIRST_AVAILABLE), getArtifactInstance()->getId()))
  694. cb->removeObject(this, h->getOwner());
  695. }
  696. BattleField CGArtifact::getBattlefield() const
  697. {
  698. return BattleField::NONE;
  699. }
  700. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  701. {
  702. if(result.winner == BattleSide::ATTACKER) //attacker won
  703. pick(hero);
  704. }
  705. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  706. {
  707. if(answer)
  708. cb->startBattle(hero, this);
  709. }
  710. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  711. {
  712. handler.serializeStruct("guardMessage", message);
  713. CArmedInstance::serializeJsonOptions(handler);
  714. if(!handler.saving && !handler.getCurrent()["guards"].Vector().empty())
  715. CCreatureSet::serializeJson(handler, "guards", 7);
  716. if(handler.saving && ID == Obj::SPELL_SCROLL)
  717. {
  718. const auto & b = getArtifactInstance()->getFirstBonus(Selector::type()(BonusType::SPELL));
  719. SpellID spellId(b->subtype.as<SpellID>());
  720. handler.serializeId("spell", spellId, SpellID::NONE);
  721. }
  722. }
  723. void CGSignBottle::initObj(vstd::RNG & rand)
  724. {
  725. //if no text is set than we pick random from the predefined ones
  726. if(message.empty())
  727. {
  728. auto vector = LIBRARY->generaltexth->findStringsWithPrefix("core.randsign");
  729. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  730. message.appendTextID(messageIdentifier);
  731. }
  732. if(ID == Obj::OCEAN_BOTTLE)
  733. {
  734. blockVisit = true;
  735. }
  736. }
  737. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  738. {
  739. InfoWindow iw;
  740. iw.player = h->getOwner();
  741. iw.text = message;
  742. cb->showInfoDialog(&iw);
  743. if(ID == Obj::OCEAN_BOTTLE)
  744. cb->removeObject(this, h->getOwner());
  745. }
  746. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  747. {
  748. handler.serializeStruct("text", message);
  749. }
  750. const IOwnableObject * CGGarrison::asOwnable() const
  751. {
  752. return this;
  753. }
  754. ResourceSet CGGarrison::dailyIncome() const
  755. {
  756. return {};
  757. }
  758. std::vector<CreatureID> CGGarrison::providedCreatures() const
  759. {
  760. return {};
  761. }
  762. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  763. {
  764. auto relations = cb->gameState().getPlayerRelations(h->tempOwner, tempOwner);
  765. if (relations == PlayerRelations::ENEMIES && stacksCount() > 0) {
  766. //TODO: Find a way to apply magic garrison effects in battle.
  767. cb->startBattle(h, this);
  768. return;
  769. }
  770. //New owner.
  771. if (relations == PlayerRelations::ENEMIES)
  772. cb->setOwner(this, h->tempOwner);
  773. cb->showGarrisonDialog(id, h->id, removableUnits);
  774. }
  775. bool CGGarrison::passableFor(PlayerColor player) const
  776. {
  777. //FIXME: identical to same method in CGTownInstance
  778. if ( !stacksCount() )//empty - anyone can visit
  779. return true;
  780. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  781. return false;
  782. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  783. return true;
  784. return false;
  785. }
  786. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  787. {
  788. if (result.winner == BattleSide::ATTACKER)
  789. onHeroVisit(hero);
  790. }
  791. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  792. {
  793. handler.serializeBool("removableUnits", removableUnits);
  794. serializeJsonOwner(handler);
  795. CArmedInstance::serializeJsonOptions(handler);
  796. }
  797. void CGGarrison::initObj(vstd::RNG &rand)
  798. {
  799. if(this->subID == MapObjectSubID::decode(this->ID, "antiMagic"))
  800. addAntimagicGarrisonBonus();
  801. }
  802. void CGGarrison::addAntimagicGarrisonBonus()
  803. {
  804. auto bonus = std::make_shared<Bonus>();
  805. bonus->type = BonusType::BLOCK_ALL_MAGIC;
  806. bonus->source = BonusSource::OBJECT_TYPE;
  807. bonus->sid = BonusSourceID(this->ID);
  808. bonus->propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  809. bonus->duration = BonusDuration::PERMANENT;
  810. this->addNewBonus(bonus);
  811. }
  812. void CGMagi::initObj(vstd::RNG & rand)
  813. {
  814. if (ID == Obj::EYE_OF_MAGI)
  815. blockVisit = true;
  816. }
  817. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  818. {
  819. if (ID == Obj::HUT_OF_MAGI)
  820. {
  821. h->showInfoDialog(61);
  822. std::vector<const CGObjectInstance *> eyes;
  823. for (const auto & object : cb->gameState().getMap().getObjects<CGMagi>())
  824. {
  825. if (object->ID == Obj::EYE_OF_MAGI && object->subID == this->subID)
  826. eyes.push_back(object);
  827. }
  828. if (!eyes.empty())
  829. {
  830. CenterView cv;
  831. cv.player = h->tempOwner;
  832. cv.focusTime = 2000;
  833. FoWChange fw;
  834. fw.player = h->tempOwner;
  835. fw.mode = ETileVisibility::REVEALED;
  836. fw.waitForDialogs = true;
  837. for(const auto & eye : eyes)
  838. {
  839. cb->getTilesInRange (fw.tiles, eye->visitablePos(), 10, ETileVisibility::HIDDEN, h->tempOwner);
  840. cb->sendAndApply(fw);
  841. cv.pos = eye->visitablePos();
  842. cb->sendAndApply(cv);
  843. }
  844. cv.pos = h->visitablePos();
  845. cv.focusTime = 0;
  846. cb->sendAndApply(cv);
  847. }
  848. }
  849. else if (ID == Obj::EYE_OF_MAGI)
  850. {
  851. h->showInfoDialog(48);
  852. }
  853. }
  854. CGBoat::CGBoat(IGameCallback * cb)
  855. : CGObjectInstance(cb)
  856. {
  857. direction = 4;
  858. layer = EPathfindingLayer::SAIL;
  859. }
  860. bool CGBoat::isCoastVisitable() const
  861. {
  862. return true;
  863. }
  864. void CGBoat::setBoardedHero(const CGHeroInstance * hero)
  865. {
  866. if (hero)
  867. boardedHeroID = hero->id;
  868. else
  869. boardedHeroID = ObjectInstanceID();
  870. }
  871. const CGHeroInstance * CGBoat::getBoardedHero() const
  872. {
  873. if (boardedHeroID.hasValue())
  874. return cb->getHero(boardedHeroID);
  875. else
  876. return nullptr;
  877. }
  878. void CGSirens::initObj(vstd::RNG & rand)
  879. {
  880. blockVisit = true;
  881. }
  882. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  883. {
  884. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID)));
  885. }
  886. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  887. {
  888. InfoWindow iw;
  889. iw.player = h->tempOwner;
  890. if(h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID))) //has already visited Sirens
  891. {
  892. iw.type = EInfoWindowMode::AUTO;
  893. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  894. }
  895. else
  896. {
  897. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  898. TExpType xp = 0;
  899. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  900. {
  901. // 1-sized stacks are not affected by sirens
  902. if (i->second->count == 1)
  903. continue;
  904. // tested H3 behavior: 30% (rounded up) of stack drowns
  905. TQuantity drown = std::ceil(i->second->count * 0.3);
  906. if(drown)
  907. {
  908. cb->changeStackCount(StackLocation(h->id, i->first), -drown);
  909. xp += drown * i->second->getType()->getMaxHealth();
  910. }
  911. }
  912. if(xp)
  913. {
  914. xp = h->calculateXp(static_cast<int>(xp));
  915. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  916. iw.text.replaceNumber(static_cast<int>(xp));
  917. cb->giveExperience(h, xp);
  918. }
  919. else
  920. {
  921. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  922. }
  923. }
  924. cb->showInfoDialog(&iw);
  925. }
  926. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  927. {
  928. // H J L K I
  929. // A x S x B
  930. // C E G F D
  931. offsets = {
  932. {-2, 0, 0}, // A
  933. {+2, 0, 0}, // B
  934. {-2, 1, 0}, // C
  935. {+2, 1, 0}, // D
  936. {-1, 1, 0}, // E
  937. {+1, 1, 0}, // F
  938. {0, 1, 0}, // G
  939. {-2, -1, 0}, // H
  940. {+2, -1, 0}, // I
  941. {-1, -1, 0}, // G
  942. {+1, -1, 0}, // K
  943. {0, -1, 0}, // L
  944. };
  945. }
  946. const IObjectInterface * CGShipyard::getObject() const
  947. {
  948. return this;
  949. }
  950. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  951. {
  952. if(cb->gameState().getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  953. cb->setOwner(this, h->tempOwner);
  954. if(shipyardStatus() != IBoatGenerator::GOOD)
  955. {
  956. InfoWindow iw;
  957. iw.type = EInfoWindowMode::AUTO;
  958. iw.player = tempOwner;
  959. getProblemText(iw.text, h);
  960. cb->showInfoDialog(&iw);
  961. }
  962. else
  963. {
  964. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  965. }
  966. }
  967. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  968. {
  969. serializeJsonOwner(handler);
  970. }
  971. BoatId CGShipyard::getBoatType() const
  972. {
  973. return createdBoat;
  974. }
  975. const IOwnableObject * CGShipyard::asOwnable() const
  976. {
  977. return this;
  978. }
  979. ResourceSet CGShipyard::dailyIncome() const
  980. {
  981. return {};
  982. }
  983. std::vector<CreatureID> CGShipyard::providedCreatures() const
  984. {
  985. return {};
  986. }
  987. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  988. {
  989. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  990. }
  991. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  992. {
  993. InfoWindow iw;
  994. iw.type = EInfoWindowMode::AUTO;
  995. iw.player = h->tempOwner;
  996. TeamState *ts = cb->gameState().getPlayerTeam(h->tempOwner);
  997. assert(ts);
  998. TeamID team = ts->id;
  999. if(!wasVisited(team))
  1000. {
  1001. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1002. cb->sendAndApply(iw);
  1003. // increment general visited obelisks counter
  1004. cb->setObjPropertyID(id, ObjProperty::OBELISK_VISITED, team);
  1005. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  1006. // mark that particular obelisk as visited for all players in the team
  1007. for(const auto & color : ts->players)
  1008. {
  1009. cb->setObjPropertyID(id, ObjProperty::VISITED, color);
  1010. }
  1011. }
  1012. else
  1013. {
  1014. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1015. cb->sendAndApply(iw);
  1016. }
  1017. }
  1018. void CGObelisk::initObj(vstd::RNG & rand)
  1019. {
  1020. cb->gameState().getMap().obeliskCount++;
  1021. }
  1022. std::string CGObelisk::getHoverText(PlayerColor player) const
  1023. {
  1024. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1025. }
  1026. std::string CGObelisk::getObjectDescription(PlayerColor player) const
  1027. {
  1028. return visitedTxt(wasVisited(player));
  1029. }
  1030. void CGObelisk::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  1031. {
  1032. switch(what)
  1033. {
  1034. case ObjProperty::OBELISK_VISITED:
  1035. {
  1036. auto progress = ++cb->gameState().getMap().obelisksVisited[identifier.as<TeamID>()];
  1037. logGlobal->debug("Player %d: obelisk progress %d / %d", identifier.getNum(), static_cast<int>(progress) , static_cast<int>(cb->gameState().getMap().obeliskCount));
  1038. if(progress > cb->gameState().getMap().obeliskCount)
  1039. {
  1040. logGlobal->error("Visited %d of %d", static_cast<int>(progress), cb->gameState().getMap().obeliskCount);
  1041. throw std::runtime_error("Player visited " + std::to_string(progress) + " obelisks out of " + std::to_string(cb->gameState().getMap().obeliskCount) + " present on map!");
  1042. }
  1043. break;
  1044. }
  1045. default:
  1046. CTeamVisited::setPropertyDer(what, identifier);
  1047. break;
  1048. }
  1049. }
  1050. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1051. {
  1052. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1053. }
  1054. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1055. {
  1056. int32_t level = stack.getType()->getLevel();
  1057. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1058. int costModifier = upgradeCostPercentage[index];
  1059. for(const auto & nid : stack.getCreature()->upgrades)
  1060. {
  1061. info.addUpgrade(nid, stack.getType(), costModifier);
  1062. }
  1063. }
  1064. std::string HillFort::getPopupText(PlayerColor player) const
  1065. {
  1066. MetaString message = MetaString::createFromRawString("{%s}\r\n\r\n%s");
  1067. message.replaceName(ID, subID);
  1068. message.replaceTextID(getDescriptionToolTip());
  1069. return message.toString();
  1070. }
  1071. std::string HillFort::getPopupText(const CGHeroInstance * hero) const
  1072. {
  1073. return getPopupText(hero->getOwner());
  1074. }
  1075. std::string HillFort::getDescriptionToolTip() const
  1076. {
  1077. return TextIdentifier(getObjectHandler()->getBaseTextID(), "description").get();
  1078. }
  1079. std::string HillFort::getUnavailableUpgradeMessage() const
  1080. {
  1081. assert(getObjectHandler()->getModScope() != "core");
  1082. return TextIdentifier(getObjectHandler()->getBaseTextID(), "unavailableUpgradeMessage").get();
  1083. }
  1084. VCMI_LIB_NAMESPACE_END