2
0

MiscObjects.cpp 34 KB

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