MiscObjects.cpp 34 KB

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