MiscObjects.cpp 35 KB

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