MiscObjects.cpp 35 KB

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