MiscObjects.cpp 33 KB

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