MiscObjects.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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 VLC->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 = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  92. putStack(SlotID(0), 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 VLC->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(" + VLC->generaltexth->restypes[producedResource.getNum()] + ")";
  139. if(stacksCount())
  140. {
  141. hoverName += "\n";
  142. hoverName += VLC->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. GameResID CGResource::resourceID() const
  224. {
  225. return getObjTypeIndex().getNum();
  226. }
  227. std::string CGResource::getHoverText(PlayerColor player) const
  228. {
  229. return VLC->generaltexth->restypes[resourceID().getNum()];
  230. }
  231. void CGResource::pickRandomObject(vstd::RNG & rand)
  232. {
  233. assert(ID == Obj::RESOURCE || ID == Obj::RANDOM_RESOURCE);
  234. if (ID == Obj::RANDOM_RESOURCE)
  235. {
  236. ID = Obj::RESOURCE;
  237. subID = rand.nextInt(EGameResID::WOOD, EGameResID::GOLD);
  238. setType(ID, subID);
  239. if (subID == EGameResID::GOLD && amount != CGResource::RANDOM_AMOUNT)
  240. amount *= CGResource::GOLD_AMOUNT_MULTIPLIER;
  241. }
  242. }
  243. void CGResource::initObj(vstd::RNG & rand)
  244. {
  245. blockVisit = true;
  246. if(amount == CGResource::RANDOM_AMOUNT)
  247. {
  248. switch(resourceID().toEnum())
  249. {
  250. case EGameResID::GOLD:
  251. amount = rand.nextInt(5, 10) * CGResource::GOLD_AMOUNT_MULTIPLIER;
  252. break;
  253. case EGameResID::WOOD: case EGameResID::ORE:
  254. amount = rand.nextInt(6, 10);
  255. break;
  256. default:
  257. amount = rand.nextInt(3, 5);
  258. break;
  259. }
  260. }
  261. }
  262. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  263. {
  264. if(stacksCount())
  265. {
  266. if(!message.empty())
  267. {
  268. BlockingDialog ynd(true,false);
  269. ynd.player = h->getOwner();
  270. ynd.text = message;
  271. cb->showBlockingDialog(this, &ynd);
  272. }
  273. else
  274. {
  275. blockingDialogAnswered(h, true); //behave as if player accepted battle
  276. }
  277. }
  278. else
  279. collectRes(h->getOwner());
  280. }
  281. void CGResource::collectRes(const PlayerColor & player) const
  282. {
  283. cb->giveResource(player, resourceID(), amount);
  284. InfoWindow sii;
  285. sii.player = player;
  286. if(!message.empty())
  287. {
  288. sii.type = EInfoWindowMode::AUTO;
  289. sii.text = message;
  290. }
  291. else
  292. {
  293. sii.type = EInfoWindowMode::INFO;
  294. sii.text.appendLocalString(EMetaText::ADVOB_TXT,113);
  295. sii.text.replaceName(resourceID());
  296. }
  297. sii.components.emplace_back(ComponentType::RESOURCE, resourceID(), amount);
  298. sii.soundID = soundBase::pickup01 + cb->gameState()->getRandomGenerator().nextInt(6);
  299. cb->showInfoDialog(&sii);
  300. cb->removeObject(this, player);
  301. }
  302. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  303. {
  304. if(result.winner == BattleSide::ATTACKER) //attacker won
  305. collectRes(hero->getOwner());
  306. }
  307. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  308. {
  309. if(answer)
  310. cb->startBattle(hero, this);
  311. }
  312. void CGResource::serializeJsonOptions(JsonSerializeFormat & handler)
  313. {
  314. CArmedInstance::serializeJsonOptions(handler);
  315. if(!handler.saving && !handler.getCurrent()["guards"].Vector().empty())
  316. CCreatureSet::serializeJson(handler, "guards", 7);
  317. handler.serializeInt("amount", amount, 0);
  318. handler.serializeStruct("guardMessage", message);
  319. }
  320. bool CGTeleport::isEntrance() const
  321. {
  322. return type == BOTH || type == ENTRANCE;
  323. }
  324. bool CGTeleport::isExit() const
  325. {
  326. return type == BOTH || type == EXIT;
  327. }
  328. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  329. {
  330. return vstd::contains(getAllEntrances(), id);
  331. }
  332. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  333. {
  334. return vstd::contains(getAllExits(), id);
  335. }
  336. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  337. {
  338. auto ret = cb->getTeleportChannelEntrances(channel);
  339. if(excludeCurrent)
  340. vstd::erase_if_present(ret, id);
  341. return ret;
  342. }
  343. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  344. {
  345. auto ret = cb->getTeleportChannelExits(channel);
  346. if(excludeCurrent)
  347. vstd::erase_if_present(ret, id);
  348. return ret;
  349. }
  350. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  351. {
  352. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  353. if(!passableExits.empty())
  354. return *RandomGeneratorUtil::nextItem(passableExits, cb->gameState()->getRandomGenerator());
  355. return ObjectInstanceID();
  356. }
  357. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  358. {
  359. return dynamic_cast<const CGTeleport *>(obj) != nullptr;
  360. }
  361. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  362. {
  363. return src && dst && src->isChannelExit(dst->id);
  364. }
  365. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  366. {
  367. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  368. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  369. return isConnected(srcObj, dstObj);
  370. }
  371. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  372. {
  373. auto * objTopVisObj = gs->map->getTile(obj->visitablePos()).topVisitableObj();
  374. if(objTopVisObj->ID == Obj::HERO)
  375. {
  376. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  377. return false;
  378. // Check if it's friendly hero or not
  379. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  380. {
  381. // Exchange between heroes only possible via subterranean gates
  382. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  383. return false;
  384. }
  385. }
  386. return true;
  387. }
  388. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  389. {
  390. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  391. {
  392. return !isExitPassable(gs, h, gs->getObj(exit));
  393. });
  394. return exits;
  395. }
  396. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  397. {
  398. std::shared_ptr<TeleportChannel> tc;
  399. if(channelsList.find(obj->channel) == channelsList.end())
  400. {
  401. tc = std::make_shared<TeleportChannel>();
  402. channelsList.insert(std::make_pair(obj->channel, tc));
  403. }
  404. else
  405. tc = channelsList[obj->channel];
  406. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  407. tc->entrances.push_back(obj->id);
  408. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  409. tc->exits.push_back(obj->id);
  410. if(!tc->entrances.empty() && !tc->exits.empty()
  411. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  412. {
  413. tc->passability = TeleportChannel::PASSABLE;
  414. }
  415. }
  416. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, MapObjectSubID SubID) const
  417. {
  418. for(auto obj : cb->gameState()->map->objects)
  419. {
  420. if(!obj)
  421. continue;
  422. const auto * teleportObj = dynamic_cast<const CGMonolith *>(cb->getObj(obj->id));
  423. if(teleportObj && vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  424. return teleportObj->channel;
  425. }
  426. return TeleportChannelID();
  427. }
  428. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  429. {
  430. TeleportDialog td(h->id, channel);
  431. if(isEntrance())
  432. {
  433. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  434. {
  435. auto exits = cb->getTeleportChannelExits(channel);
  436. for(const auto & exit : exits)
  437. {
  438. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  439. }
  440. }
  441. if(cb->isTeleportChannelImpassable(channel))
  442. {
  443. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), anchorPos().toString());
  444. td.impassable = true;
  445. }
  446. else if(getRandomExit(h) == ObjectInstanceID())
  447. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), anchorPos().toString());
  448. }
  449. else
  450. h->showInfoDialog(70);
  451. cb->showTeleportDialog(&td);
  452. }
  453. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  454. {
  455. int3 dPos;
  456. auto randomExit = getRandomExit(hero);
  457. auto realExits = getAllExits(true);
  458. if(!isEntrance() // Do nothing if hero visited exit only object
  459. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  460. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  461. {
  462. return;
  463. }
  464. else if(vstd::isValidIndex(exits, answer))
  465. dPos = exits[answer].second;
  466. else
  467. dPos = cb->getObj(randomExit)->visitablePos();
  468. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  469. }
  470. void CGMonolith::initObj(vstd::RNG & rand)
  471. {
  472. std::vector<Obj> IDs;
  473. IDs.push_back(ID);
  474. switch(ID.toEnum())
  475. {
  476. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  477. type = ENTRANCE;
  478. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  479. break;
  480. case Obj::MONOLITH_ONE_WAY_EXIT:
  481. type = EXIT;
  482. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  483. break;
  484. case Obj::MONOLITH_TWO_WAY:
  485. default:
  486. type = BOTH;
  487. break;
  488. }
  489. channel = findMeChannel(IDs, subID);
  490. if(channel == TeleportChannelID())
  491. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  492. addToChannel(cb->gameState()->map->teleportChannels, this);
  493. }
  494. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  495. {
  496. TeleportDialog td(h->id, channel);
  497. if(cb->isTeleportChannelImpassable(channel))
  498. {
  499. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  500. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), anchorPos().toString());
  501. td.impassable = true;
  502. }
  503. else
  504. {
  505. auto exit = getRandomExit(h);
  506. td.exits.push_back(std::make_pair(exit, cb->getObj(exit)->visitablePos()));
  507. }
  508. cb->showTeleportDialog(&td);
  509. }
  510. void CGSubterraneanGate::initObj(vstd::RNG & rand)
  511. {
  512. type = BOTH;
  513. }
  514. void CGSubterraneanGate::postInit(IGameCallback * cb) //matches subterranean gates into pairs
  515. {
  516. //split on underground and surface gates
  517. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  518. for(auto & obj : cb->gameState()->map->objects)
  519. {
  520. if(!obj)
  521. continue;
  522. auto * hlp = dynamic_cast<CGSubterraneanGate *>(cb->gameState()->getObjInstance(obj->id));
  523. if(hlp)
  524. gatesSplit[hlp->visitablePos().z].push_back(hlp);
  525. }
  526. //sort by position
  527. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  528. {
  529. return a->visitablePos() < b->visitablePos();
  530. });
  531. auto assignToChannel = [&](CGSubterraneanGate * obj)
  532. {
  533. if(obj->channel == TeleportChannelID())
  534. { // if object not linked to channel then create new channel
  535. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  536. addToChannel(cb->gameState()->map->teleportChannels, obj);
  537. }
  538. };
  539. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  540. {
  541. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  542. //find nearest underground exit
  543. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  544. for(int j = 0; j < gatesSplit[1].size(); j++)
  545. {
  546. CGSubterraneanGate *checked = gatesSplit[1][j];
  547. if(checked->channel != TeleportChannelID())
  548. continue;
  549. si32 hlp = checked->visitablePos().dist2dSQ(objCurrent->visitablePos());
  550. if(hlp < best.second)
  551. {
  552. best.first = j;
  553. best.second = hlp;
  554. }
  555. }
  556. assignToChannel(objCurrent);
  557. if(best.first >= 0) //found pair
  558. {
  559. gatesSplit[1][best.first]->channel = objCurrent->channel;
  560. addToChannel(cb->gameState()->map->teleportChannels, gatesSplit[1][best.first]);
  561. }
  562. }
  563. // we should assign empty channels to underground gates if they don't have matching overground gates
  564. for(auto & i : gatesSplit[1])
  565. assignToChannel(i);
  566. }
  567. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  568. {
  569. TeleportDialog td(h->id, channel);
  570. if(cb->isTeleportChannelImpassable(channel))
  571. {
  572. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), anchorPos().toString());
  573. td.impassable = true;
  574. }
  575. else if(getRandomExit(h) == ObjectInstanceID())
  576. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), anchorPos().toString());
  577. if(!isProtected(h))
  578. {
  579. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  580. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  581. {
  582. if(h->getPower(targetstack) > h->getPower(i->first))
  583. targetstack = (i->first);
  584. }
  585. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  586. vstd::amax(countToTake, 1);
  587. InfoWindow iw;
  588. iw.type = EInfoWindowMode::AUTO;
  589. iw.player = h->tempOwner;
  590. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 168);
  591. iw.components.emplace_back(ComponentType::CREATURE, h->getCreature(targetstack)->getId(), -countToTake);
  592. cb->showInfoDialog(&iw);
  593. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  594. }
  595. else
  596. {
  597. auto exits = getAllExits();
  598. for(const auto & exit : exits)
  599. {
  600. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  601. for(const auto & bPos : blockedPosList)
  602. td.exits.push_back(std::make_pair(exit, bPos));
  603. }
  604. }
  605. cb->showTeleportDialog(&td);
  606. }
  607. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  608. {
  609. int3 dPos;
  610. auto realExits = getAllExits();
  611. if(exits.empty() && realExits.empty())
  612. return;
  613. else if(vstd::isValidIndex(exits, answer))
  614. dPos = exits[answer].second;
  615. else
  616. {
  617. auto exit = getRandomExit(hero);
  618. if(exit == ObjectInstanceID())
  619. return;
  620. const auto * obj = cb->getObj(exit);
  621. std::set<int3> tiles = obj->getBlockedPos();
  622. dPos = *RandomGeneratorUtil::nextItem(tiles, cb->gameState()->getRandomGenerator());
  623. }
  624. cb->moveHero(hero->id, hero->convertFromVisitablePos(dPos), EMovementMode::MONOLITH);
  625. }
  626. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  627. {
  628. return h->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION)
  629. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1)
  630. || (h->stacksCount() == 0 && h->commander && h->commander->alive);
  631. }
  632. ArtifactID CGArtifact::getArtifact() const
  633. {
  634. if(ID == Obj::SPELL_SCROLL)
  635. return ArtifactID::SPELL_SCROLL;
  636. else
  637. return getObjTypeIndex().getNum();
  638. }
  639. void CGArtifact::pickRandomObject(vstd::RNG & rand)
  640. {
  641. switch(ID.toEnum())
  642. {
  643. case MapObjectID::RANDOM_ART:
  644. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC);
  645. break;
  646. case MapObjectID::RANDOM_TREASURE_ART:
  647. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_TREASURE);
  648. break;
  649. case MapObjectID::RANDOM_MINOR_ART:
  650. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_MINOR);
  651. break;
  652. case MapObjectID::RANDOM_MAJOR_ART:
  653. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_MAJOR);
  654. break;
  655. case MapObjectID::RANDOM_RELIC_ART:
  656. subID = cb->gameState()->pickRandomArtifact(rand, CArtifact::ART_RELIC);
  657. break;
  658. }
  659. if (ID != MapObjectID::SPELL_SCROLL && ID != MapObjectID::ARTIFACT)
  660. {
  661. ID = MapObjectID::ARTIFACT;
  662. setType(ID, subID);
  663. }
  664. else if (ID != MapObjectID::SPELL_SCROLL)
  665. ID = MapObjectID::ARTIFACT;
  666. }
  667. void CGArtifact::initObj(vstd::RNG & rand)
  668. {
  669. blockVisit = true;
  670. if(ID == Obj::ARTIFACT)
  671. {
  672. if (!storedArtifact)
  673. {
  674. storedArtifact = ArtifactUtils::createArtifact(ArtifactID());
  675. cb->gameState()->map->addNewArtifactInstance(storedArtifact);
  676. }
  677. if(!storedArtifact->getType())
  678. storedArtifact->setType(getArtifact().toArtifact());
  679. }
  680. if(ID == Obj::SPELL_SCROLL)
  681. subID = 1;
  682. assert(storedArtifact->getType());
  683. assert(!storedArtifact->getParentNodes().empty());
  684. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  685. }
  686. std::string CGArtifact::getObjectName() const
  687. {
  688. return VLC->artifacts()->getById(getArtifact())->getNameTranslated();
  689. }
  690. std::string CGArtifact::getPopupText(PlayerColor player) const
  691. {
  692. if (settings["general"]["enableUiEnhancements"].Bool())
  693. {
  694. std::string description = VLC->artifacts()->getById(getArtifact())->getDescriptionTranslated();
  695. if (getArtifact() == ArtifactID::SPELL_SCROLL)
  696. ArtifactUtils::insertScrrollSpellName(description, SpellID::NONE); // erase text placeholder
  697. return description;
  698. }
  699. else
  700. return getObjectName();
  701. }
  702. std::string CGArtifact::getPopupText(const CGHeroInstance * hero) const
  703. {
  704. return getPopupText(hero->getOwner());
  705. }
  706. std::vector<Component> CGArtifact::getPopupComponents(PlayerColor player) const
  707. {
  708. return {
  709. Component(ComponentType::ARTIFACT, getArtifact())
  710. };
  711. }
  712. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  713. {
  714. if(!stacksCount())
  715. {
  716. InfoWindow iw;
  717. iw.type = EInfoWindowMode::AUTO;
  718. iw.player = h->tempOwner;
  719. if(storedArtifact->getType()->canBePutAt(h))
  720. {
  721. switch (ID.toEnum())
  722. {
  723. case Obj::ARTIFACT:
  724. {
  725. iw.components.emplace_back(ComponentType::ARTIFACT, getArtifact());
  726. if(!message.empty())
  727. iw.text = message;
  728. else
  729. iw.text.appendTextID(getArtifact().toArtifact()->getEventTextID());
  730. }
  731. break;
  732. case Obj::SPELL_SCROLL:
  733. {
  734. SpellID spell = storedArtifact->getScrollSpellID();
  735. iw.components.emplace_back(ComponentType::SPELL, spell);
  736. if(!message.empty())
  737. iw.text = message;
  738. else
  739. {
  740. iw.text.appendLocalString(EMetaText::ADVOB_TXT,135);
  741. iw.text.replaceName(spell);
  742. }
  743. }
  744. break;
  745. }
  746. }
  747. else
  748. {
  749. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 2);
  750. }
  751. cb->showInfoDialog(&iw);
  752. pick(h);
  753. }
  754. else
  755. {
  756. switch(ID.toEnum())
  757. {
  758. case Obj::ARTIFACT:
  759. {
  760. BlockingDialog ynd(true,false);
  761. ynd.player = h->getOwner();
  762. if(!message.empty())
  763. ynd.text = message;
  764. else
  765. {
  766. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  767. ynd.text.appendLocalString(EMetaText::GENERAL_TXT, 420);
  768. ynd.text.replaceRawString("");
  769. ynd.text.replaceRawString(getArmyDescription());
  770. ynd.text.replaceLocalString(EMetaText::GENERAL_TXT, 43); // creatures
  771. }
  772. cb->showBlockingDialog(this, &ynd);
  773. }
  774. break;
  775. case Obj::SPELL_SCROLL:
  776. {
  777. if(!message.empty())
  778. {
  779. BlockingDialog ynd(true,false);
  780. ynd.player = h->getOwner();
  781. ynd.text = message;
  782. cb->showBlockingDialog(this, &ynd);
  783. }
  784. else
  785. blockingDialogAnswered(h, true);
  786. }
  787. break;
  788. }
  789. }
  790. }
  791. void CGArtifact::pick(const CGHeroInstance * h) const
  792. {
  793. if(cb->putArtifact(ArtifactLocation(h->id, ArtifactPosition::FIRST_AVAILABLE), storedArtifact->getId()))
  794. cb->removeObject(this, h->getOwner());
  795. }
  796. BattleField CGArtifact::getBattlefield() const
  797. {
  798. return BattleField::NONE;
  799. }
  800. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  801. {
  802. if(result.winner == BattleSide::ATTACKER) //attacker won
  803. pick(hero);
  804. }
  805. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  806. {
  807. if(answer)
  808. cb->startBattle(hero, this);
  809. }
  810. void CGArtifact::afterAddToMap(CMap * map)
  811. {
  812. //Artifacts from map objects are never removed
  813. //FIXME: This should be revertible in map editor
  814. if(ID == Obj::SPELL_SCROLL && storedArtifact && storedArtifact->getId().getNum() < 0)
  815. map->addNewArtifactInstance(storedArtifact);
  816. }
  817. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  818. {
  819. handler.serializeStruct("guardMessage", message);
  820. CArmedInstance::serializeJsonOptions(handler);
  821. if(!handler.saving && !handler.getCurrent()["guards"].Vector().empty())
  822. CCreatureSet::serializeJson(handler, "guards", 7);
  823. if(handler.saving && ID == Obj::SPELL_SCROLL)
  824. {
  825. const auto & b = storedArtifact->getFirstBonus(Selector::type()(BonusType::SPELL));
  826. SpellID spellId(b->subtype.as<SpellID>());
  827. handler.serializeId("spell", spellId, SpellID::NONE);
  828. }
  829. }
  830. void CGSignBottle::initObj(vstd::RNG & rand)
  831. {
  832. //if no text is set than we pick random from the predefined ones
  833. if(message.empty())
  834. {
  835. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  836. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  837. message.appendTextID(messageIdentifier);
  838. }
  839. if(ID == Obj::OCEAN_BOTTLE)
  840. {
  841. blockVisit = true;
  842. }
  843. }
  844. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  845. {
  846. InfoWindow iw;
  847. iw.player = h->getOwner();
  848. iw.text = message;
  849. cb->showInfoDialog(&iw);
  850. if(ID == Obj::OCEAN_BOTTLE)
  851. cb->removeObject(this, h->getOwner());
  852. }
  853. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  854. {
  855. handler.serializeStruct("text", message);
  856. }
  857. const IOwnableObject * CGGarrison::asOwnable() const
  858. {
  859. return this;
  860. }
  861. ResourceSet CGGarrison::dailyIncome() const
  862. {
  863. return {};
  864. }
  865. std::vector<CreatureID> CGGarrison::providedCreatures() const
  866. {
  867. return {};
  868. }
  869. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  870. {
  871. auto relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  872. if (relations == PlayerRelations::ENEMIES && stacksCount() > 0) {
  873. //TODO: Find a way to apply magic garrison effects in battle.
  874. cb->startBattle(h, this);
  875. return;
  876. }
  877. //New owner.
  878. if (relations == PlayerRelations::ENEMIES)
  879. cb->setOwner(this, h->tempOwner);
  880. cb->showGarrisonDialog(id, h->id, removableUnits);
  881. }
  882. bool CGGarrison::passableFor(PlayerColor player) const
  883. {
  884. //FIXME: identical to same method in CGTownInstance
  885. if ( !stacksCount() )//empty - anyone can visit
  886. return true;
  887. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  888. return false;
  889. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  890. return true;
  891. return false;
  892. }
  893. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  894. {
  895. if (result.winner == BattleSide::ATTACKER)
  896. onHeroVisit(hero);
  897. }
  898. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  899. {
  900. handler.serializeBool("removableUnits", removableUnits);
  901. serializeJsonOwner(handler);
  902. CArmedInstance::serializeJsonOptions(handler);
  903. }
  904. void CGGarrison::initObj(vstd::RNG &rand)
  905. {
  906. if(this->subID == MapObjectSubID::decode(this->ID, "antiMagic"))
  907. addAntimagicGarrisonBonus();
  908. }
  909. void CGGarrison::addAntimagicGarrisonBonus()
  910. {
  911. auto bonus = std::make_shared<Bonus>();
  912. bonus->type = BonusType::BLOCK_ALL_MAGIC;
  913. bonus->source = BonusSource::OBJECT_TYPE;
  914. bonus->sid = BonusSourceID(this->ID);
  915. bonus->propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  916. bonus->duration = BonusDuration::PERMANENT;
  917. this->addNewBonus(bonus);
  918. }
  919. void CGMagi::initObj(vstd::RNG & rand)
  920. {
  921. if (ID == Obj::EYE_OF_MAGI)
  922. blockVisit = true;
  923. }
  924. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  925. {
  926. if (ID == Obj::HUT_OF_MAGI)
  927. {
  928. h->showInfoDialog(61);
  929. std::vector<const CGObjectInstance *> eyes;
  930. for (auto object : cb->gameState()->map->objects)
  931. {
  932. if (object && object->ID == Obj::EYE_OF_MAGI && object->subID == this->subID)
  933. eyes.push_back(object);
  934. }
  935. if (!eyes.empty())
  936. {
  937. CenterView cv;
  938. cv.player = h->tempOwner;
  939. cv.focusTime = 2000;
  940. FoWChange fw;
  941. fw.player = h->tempOwner;
  942. fw.mode = ETileVisibility::REVEALED;
  943. fw.waitForDialogs = true;
  944. for(const auto & eye : eyes)
  945. {
  946. cb->getTilesInRange (fw.tiles, eye->visitablePos(), 10, ETileVisibility::HIDDEN, h->tempOwner);
  947. cb->sendAndApply(fw);
  948. cv.pos = eye->visitablePos();
  949. cb->sendAndApply(cv);
  950. }
  951. cv.pos = h->visitablePos();
  952. cv.focusTime = 0;
  953. cb->sendAndApply(cv);
  954. }
  955. }
  956. else if (ID == Obj::EYE_OF_MAGI)
  957. {
  958. h->showInfoDialog(48);
  959. }
  960. }
  961. CGBoat::CGBoat(IGameCallback * cb)
  962. : CGObjectInstance(cb)
  963. {
  964. hero = nullptr;
  965. direction = 4;
  966. layer = EPathfindingLayer::SAIL;
  967. }
  968. bool CGBoat::isCoastVisitable() const
  969. {
  970. return true;
  971. }
  972. void CGSirens::initObj(vstd::RNG & rand)
  973. {
  974. blockVisit = true;
  975. }
  976. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  977. {
  978. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID)));
  979. }
  980. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  981. {
  982. InfoWindow iw;
  983. iw.player = h->tempOwner;
  984. if(h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(ID))) //has already visited Sirens
  985. {
  986. iw.type = EInfoWindowMode::AUTO;
  987. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  988. }
  989. else
  990. {
  991. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  992. TExpType xp = 0;
  993. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  994. {
  995. // 1-sized stacks are not affected by sirens
  996. if (i->second->count == 1)
  997. continue;
  998. // tested H3 behavior: 30% (rounded up) of stack drowns
  999. TQuantity drown = std::ceil(i->second->count * 0.3);
  1000. if(drown)
  1001. {
  1002. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1003. xp += drown * i->second->getType()->getMaxHealth();
  1004. }
  1005. }
  1006. if(xp)
  1007. {
  1008. xp = h->calculateXp(static_cast<int>(xp));
  1009. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  1010. iw.text.replaceNumber(static_cast<int>(xp));
  1011. cb->giveExperience(h, xp);
  1012. }
  1013. else
  1014. {
  1015. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  1016. }
  1017. }
  1018. cb->showInfoDialog(&iw);
  1019. }
  1020. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1021. {
  1022. // H J L K I
  1023. // A x S x B
  1024. // C E G F D
  1025. offsets = {
  1026. {-2, 0, 0}, // A
  1027. {+2, 0, 0}, // B
  1028. {-2, 1, 0}, // C
  1029. {+2, 1, 0}, // D
  1030. {-1, 1, 0}, // E
  1031. {+1, 1, 0}, // F
  1032. {0, 1, 0}, // G
  1033. {-2, -1, 0}, // H
  1034. {+2, -1, 0}, // I
  1035. {-1, -1, 0}, // G
  1036. {+1, -1, 0}, // K
  1037. {0, -1, 0}, // L
  1038. };
  1039. }
  1040. const IObjectInterface * CGShipyard::getObject() const
  1041. {
  1042. return this;
  1043. }
  1044. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1045. {
  1046. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  1047. cb->setOwner(this, h->tempOwner);
  1048. if(shipyardStatus() != IBoatGenerator::GOOD)
  1049. {
  1050. InfoWindow iw;
  1051. iw.type = EInfoWindowMode::AUTO;
  1052. iw.player = tempOwner;
  1053. getProblemText(iw.text, h);
  1054. cb->showInfoDialog(&iw);
  1055. }
  1056. else
  1057. {
  1058. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  1059. }
  1060. }
  1061. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1062. {
  1063. serializeJsonOwner(handler);
  1064. }
  1065. BoatId CGShipyard::getBoatType() const
  1066. {
  1067. return createdBoat;
  1068. }
  1069. const IOwnableObject * CGShipyard::asOwnable() const
  1070. {
  1071. return this;
  1072. }
  1073. ResourceSet CGShipyard::dailyIncome() const
  1074. {
  1075. return {};
  1076. }
  1077. std::vector<CreatureID> CGShipyard::providedCreatures() const
  1078. {
  1079. return {};
  1080. }
  1081. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1082. {
  1083. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  1084. }
  1085. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1086. {
  1087. InfoWindow iw;
  1088. iw.type = EInfoWindowMode::AUTO;
  1089. iw.player = h->tempOwner;
  1090. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1091. assert(ts);
  1092. TeamID team = ts->id;
  1093. if(!wasVisited(team))
  1094. {
  1095. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1096. cb->sendAndApply(iw);
  1097. // increment general visited obelisks counter
  1098. cb->setObjPropertyID(id, ObjProperty::OBELISK_VISITED, team);
  1099. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  1100. // mark that particular obelisk as visited for all players in the team
  1101. for(const auto & color : ts->players)
  1102. {
  1103. cb->setObjPropertyID(id, ObjProperty::VISITED, color);
  1104. }
  1105. }
  1106. else
  1107. {
  1108. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1109. cb->sendAndApply(iw);
  1110. }
  1111. }
  1112. void CGObelisk::initObj(vstd::RNG & rand)
  1113. {
  1114. cb->gameState()->map->obeliskCount++;
  1115. }
  1116. std::string CGObelisk::getHoverText(PlayerColor player) const
  1117. {
  1118. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1119. }
  1120. std::string CGObelisk::getObjectDescription(PlayerColor player) const
  1121. {
  1122. return visitedTxt(wasVisited(player));
  1123. }
  1124. void CGObelisk::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  1125. {
  1126. switch(what)
  1127. {
  1128. case ObjProperty::OBELISK_VISITED:
  1129. {
  1130. auto progress = ++cb->gameState()->map->obelisksVisited[identifier.as<TeamID>()];
  1131. logGlobal->debug("Player %d: obelisk progress %d / %d", identifier.getNum(), static_cast<int>(progress) , static_cast<int>(cb->gameState()->map->obeliskCount));
  1132. if(progress > cb->gameState()->map->obeliskCount)
  1133. {
  1134. logGlobal->error("Visited %d of %d", static_cast<int>(progress), cb->gameState()->map->obeliskCount);
  1135. throw std::runtime_error("Player visited " + std::to_string(progress) + " obelisks out of " + std::to_string(cb->gameState()->map->obeliskCount) + " present on map!");
  1136. }
  1137. break;
  1138. }
  1139. default:
  1140. CTeamVisited::setPropertyDer(what, identifier);
  1141. break;
  1142. }
  1143. }
  1144. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1145. {
  1146. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1147. }
  1148. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1149. {
  1150. int32_t level = stack.getType()->getLevel();
  1151. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1152. int costModifier = upgradeCostPercentage[index];
  1153. for(const auto & nid : stack.getCreature()->upgrades)
  1154. {
  1155. info.addUpgrade(nid, stack.getType(), costModifier);
  1156. }
  1157. }
  1158. std::string HillFort::getPopupText(PlayerColor player) const
  1159. {
  1160. MetaString message = MetaString::createFromRawString("{%s}\r\n\r\n%s");
  1161. message.replaceName(ID, subID);
  1162. message.replaceTextID(getDescriptionToolTip());
  1163. return message.toString();
  1164. }
  1165. std::string HillFort::getPopupText(const CGHeroInstance * hero) const
  1166. {
  1167. return getPopupText(hero->getOwner());
  1168. }
  1169. std::string HillFort::getDescriptionToolTip() const
  1170. {
  1171. return TextIdentifier(getObjectHandler()->getBaseTextID(), "description").get();
  1172. }
  1173. std::string HillFort::getUnavailableUpgradeMessage() const
  1174. {
  1175. assert(getObjectHandler()->getModScope() != "core");
  1176. return TextIdentifier(getObjectHandler()->getBaseTextID(), "unavailableUpgradeMessage").get();
  1177. }
  1178. VCMI_LIB_NAMESPACE_END