MiscObjects.cpp 34 KB

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