2
0

MiscObjects.cpp 34 KB

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