MiscObjects.cpp 33 KB

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