MiscObjects.cpp 34 KB

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