MiscObjects.cpp 32 KB

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