MiscObjects.cpp 35 KB

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