MiscObjects.cpp 32 KB

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