MiscObjects.cpp 36 KB

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