MiscObjects.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  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 CGWitchHut::initObj(CRandomGenerator & rand)
  738. {
  739. if (allowedAbilities.empty()) //this can happen for RMG and RoE maps.
  740. {
  741. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  742. // Necromancy and Leadership can't be learned by default
  743. defaultAllowed[SecondarySkill::NECROMANCY] = false;
  744. defaultAllowed[SecondarySkill::LEADERSHIP] = false;
  745. for(int i = 0; i < defaultAllowed.size(); i++)
  746. if (defaultAllowed[i] && cb->isAllowed(2, i))
  747. allowedAbilities.insert(SecondarySkill(i));
  748. }
  749. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, rand);
  750. }
  751. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  752. {
  753. InfoWindow iw;
  754. iw.type = EInfoWindowMode::AUTO;
  755. iw.player = h->getOwner();
  756. if(!wasVisited(h->tempOwner))
  757. cb->setObjProperty(id, CGWitchHut::OBJPROP_VISITED, h->tempOwner.getNum());
  758. ui32 txt_id;
  759. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  760. {
  761. txt_id =172;
  762. }
  763. else if(!h->canLearnSkill()) //already all skills slots used
  764. {
  765. txt_id = 173;
  766. }
  767. else //give sec skill
  768. {
  769. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, ability, 1, 0);
  770. txt_id = 171;
  771. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  772. }
  773. iw.text.appendLocalString(EMetaText::ADVOB_TXT,txt_id);
  774. iw.text.replaceLocalString(EMetaText::SEC_SKILL_NAME, ability);
  775. cb->showInfoDialog(&iw);
  776. }
  777. std::string CGWitchHut::getHoverText(PlayerColor player) const
  778. {
  779. std::string hoverName = getObjectName();
  780. if(wasVisited(player))
  781. {
  782. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  783. boost::algorithm::replace_first(hoverName, "%s", VLC->skillh->getByIndex(ability)->getNameTranslated());
  784. }
  785. return hoverName;
  786. }
  787. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  788. {
  789. std::string hoverName = getHoverText(hero->tempOwner);
  790. if(wasVisited(hero->tempOwner) && hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  791. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  792. return hoverName;
  793. }
  794. void CGWitchHut::serializeJsonOptions(JsonSerializeFormat & handler)
  795. {
  796. //TODO: unify allowed abilities with others - make them std::vector<bool>
  797. std::vector<bool> temp;
  798. size_t skillCount = VLC->skillh->size();
  799. temp.resize(skillCount, false);
  800. auto standard = VLC->skillh->getDefaultAllowed(); //todo: for WitchHut default is all except Leadership and Necromancy
  801. if(handler.saving)
  802. {
  803. for(SecondarySkill i(0); i < SecondarySkill(skillCount); ++i)
  804. if(vstd::contains(allowedAbilities, i))
  805. temp[i] = true;
  806. }
  807. handler.serializeLIC("allowedSkills", &CSkillHandler::decodeSkill, &CSkillHandler::encodeSkill, standard, temp);
  808. if(!handler.saving)
  809. {
  810. allowedAbilities.clear();
  811. for(si32 i = 0; i < skillCount; ++i)
  812. if(temp[i])
  813. allowedAbilities.insert(SecondarySkill(i));
  814. }
  815. }
  816. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  817. {
  818. InfoWindow iw;
  819. iw.type = EInfoWindowMode::AUTO;
  820. iw.player = h->tempOwner;
  821. switch (ID)
  822. {
  823. case Obj::REDWOOD_OBSERVATORY:
  824. case Obj::PILLAR_OF_FIRE:
  825. {
  826. iw.text.appendLocalString(EMetaText::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  827. FoWChange fw;
  828. fw.player = h->tempOwner;
  829. fw.mode = 1;
  830. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  831. cb->sendAndApply (&fw);
  832. break;
  833. }
  834. case Obj::COVER_OF_DARKNESS:
  835. {
  836. iw.text.appendLocalString (EMetaText::ADVOB_TXT, 31);
  837. for (auto & player : cb->gameState()->players)
  838. {
  839. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  840. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  841. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  842. }
  843. break;
  844. }
  845. }
  846. cb->showInfoDialog(&iw);
  847. }
  848. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  849. {
  850. if(spell == SpellID::NONE)
  851. {
  852. logGlobal->error("Not initialized shrine visited!");
  853. return;
  854. }
  855. if(!wasVisited(h->tempOwner))
  856. cb->setObjProperty(id, CGShrine::OBJPROP_VISITED, h->tempOwner.getNum());
  857. InfoWindow iw;
  858. iw.type = EInfoWindowMode::AUTO;
  859. iw.player = h->getOwner();
  860. iw.text = visitText;
  861. iw.text.appendLocalString(EMetaText::SPELL_NAME,spell);
  862. iw.text.appendRawString(".");
  863. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  864. {
  865. iw.text.appendLocalString(EMetaText::ADVOB_TXT,131);
  866. }
  867. else if(h->spellbookContainsSpell(spell))//hero already knows the spell
  868. {
  869. iw.text.appendLocalString(EMetaText::ADVOB_TXT,174);
  870. }
  871. else if(spell.toSpell()->getLevel() > h->maxSpellLevel()) //it's third level spell and hero doesn't have wisdom
  872. {
  873. iw.text.appendLocalString(EMetaText::ADVOB_TXT,130);
  874. }
  875. else //give spell
  876. {
  877. std::set<SpellID> spells;
  878. spells.insert(spell);
  879. cb->changeSpells(h, true, spells);
  880. iw.components.emplace_back(Component::EComponentType::SPELL, spell, 0, 0);
  881. }
  882. cb->showInfoDialog(&iw);
  883. }
  884. void CGShrine::initObj(CRandomGenerator & rand)
  885. {
  886. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  887. }
  888. std::string CGShrine::getHoverText(PlayerColor player) const
  889. {
  890. std::string hoverName = getObjectName();
  891. if(wasVisited(player))
  892. {
  893. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  894. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->getNameTranslated());
  895. }
  896. return hoverName;
  897. }
  898. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  899. {
  900. std::string hoverName = getHoverText(hero->tempOwner);
  901. if(wasVisited(hero->tempOwner) && hero->spellbookContainsSpell(spell)) //know what spell there is and hero knows that spell
  902. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  903. return hoverName;
  904. }
  905. void CGShrine::serializeJsonOptions(JsonSerializeFormat & handler)
  906. {
  907. handler.serializeId("spell", spell, SpellID::NONE);
  908. }
  909. void CGSignBottle::initObj(CRandomGenerator & rand)
  910. {
  911. //if no text is set than we pick random from the predefined ones
  912. if(message.empty())
  913. {
  914. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  915. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  916. message.appendTextID(TextIdentifier("core", "randsign", messageIdentifier).get());
  917. }
  918. if(ID == Obj::OCEAN_BOTTLE)
  919. {
  920. blockVisit = true;
  921. }
  922. }
  923. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  924. {
  925. InfoWindow iw;
  926. iw.player = h->getOwner();
  927. iw.text = message;
  928. cb->showInfoDialog(&iw);
  929. if(ID == Obj::OCEAN_BOTTLE)
  930. cb->removeObject(this, h->getOwner());
  931. }
  932. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  933. {
  934. handler.serializeStruct("text", message);
  935. }
  936. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  937. {
  938. EBonusType type = bonusType;
  939. int bid = bonusID;
  940. //check if the bonus if applicable, if not - give primary skill (always possible)
  941. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  942. 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)
  943. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  944. {
  945. type = PRIM_SKILL;
  946. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  947. }
  948. InfoWindow iw;
  949. iw.type = EInfoWindowMode::AUTO;
  950. iw.player = h->getOwner();
  951. iw.text.appendLocalString(EMetaText::ADVOB_TXT,115);
  952. switch (type)
  953. {
  954. case PRIM_SKILL:
  955. cb->changePrimSkill(h,static_cast<PrimarySkill>(bid),+1);
  956. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, bid, +1, 0);
  957. break;
  958. case SECONDARY_SKILL:
  959. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  960. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, bid, ssl + 1, 0);
  961. break;
  962. case SPELL:
  963. {
  964. std::set<SpellID> hlp;
  965. hlp.insert(SpellID(bid));
  966. cb->changeSpells(h,true,hlp);
  967. iw.components.emplace_back(Component::EComponentType::SPELL, bid, 0, 0);
  968. }
  969. break;
  970. default:
  971. logGlobal->error("Error: wrong bonus type (%d) for Scholar!\n", static_cast<int>(type));
  972. return;
  973. }
  974. cb->showInfoDialog(&iw);
  975. cb->removeObject(this, h->getOwner());
  976. }
  977. void CGScholar::initObj(CRandomGenerator & rand)
  978. {
  979. blockVisit = true;
  980. if(bonusType == RANDOM)
  981. {
  982. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  983. switch(bonusType)
  984. {
  985. case PRIM_SKILL:
  986. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  987. break;
  988. case SECONDARY_SKILL:
  989. bonusID = rand.nextInt(static_cast<int>(VLC->skillh->size()) - 1);
  990. break;
  991. case SPELL:
  992. std::vector<SpellID> possibilities;
  993. cb->getAllowedSpells (possibilities);
  994. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  995. break;
  996. }
  997. }
  998. }
  999. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  1000. {
  1001. if(handler.saving)
  1002. {
  1003. std::string value;
  1004. switch(bonusType)
  1005. {
  1006. case PRIM_SKILL:
  1007. value = NPrimarySkill::names[bonusID];
  1008. handler.serializeString("rewardPrimSkill", value);
  1009. break;
  1010. case SECONDARY_SKILL:
  1011. value = CSkillHandler::encodeSkill(bonusID);
  1012. handler.serializeString("rewardSkill", value);
  1013. break;
  1014. case SPELL:
  1015. value = SpellID::encode(bonusID);
  1016. handler.serializeString("rewardSpell", value);
  1017. break;
  1018. case RANDOM:
  1019. break;
  1020. }
  1021. }
  1022. else
  1023. {
  1024. //TODO: unify
  1025. const JsonNode & json = handler.getCurrent();
  1026. bonusType = RANDOM;
  1027. if(!json["rewardPrimSkill"].String().empty())
  1028. {
  1029. auto raw = VLC->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "primSkill", json["rewardPrimSkill"].String());
  1030. if(raw)
  1031. {
  1032. bonusType = PRIM_SKILL;
  1033. bonusID = raw.value();
  1034. }
  1035. }
  1036. else if(!json["rewardSkill"].String().empty())
  1037. {
  1038. auto raw = VLC->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "skill", json["rewardSkill"].String());
  1039. if(raw)
  1040. {
  1041. bonusType = SECONDARY_SKILL;
  1042. bonusID = raw.value();
  1043. }
  1044. }
  1045. else if(!json["rewardSpell"].String().empty())
  1046. {
  1047. auto raw = VLC->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "spell", json["rewardSpell"].String());
  1048. if(raw)
  1049. {
  1050. bonusType = SPELL;
  1051. bonusID = raw.value();
  1052. }
  1053. }
  1054. }
  1055. }
  1056. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1057. {
  1058. auto relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1059. if (relations == PlayerRelations::ENEMIES && stacksCount() > 0) {
  1060. //TODO: Find a way to apply magic garrison effects in battle.
  1061. cb->startBattleI(h, this);
  1062. return;
  1063. }
  1064. //New owner.
  1065. if (relations == PlayerRelations::ENEMIES)
  1066. cb->setOwner(this, h->tempOwner);
  1067. cb->showGarrisonDialog(id, h->id, removableUnits);
  1068. }
  1069. bool CGGarrison::passableFor(PlayerColor player) const
  1070. {
  1071. //FIXME: identical to same method in CGTownInstance
  1072. if ( !stacksCount() )//empty - anyone can visit
  1073. return true;
  1074. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1075. return false;
  1076. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1077. return true;
  1078. return false;
  1079. }
  1080. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1081. {
  1082. if (result.winner == 0)
  1083. onHeroVisit(hero);
  1084. }
  1085. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1086. {
  1087. handler.serializeBool("removableUnits", removableUnits);
  1088. serializeJsonOwner(handler);
  1089. CArmedInstance::serializeJsonOptions(handler);
  1090. }
  1091. void CGMagi::reset()
  1092. {
  1093. eyelist.clear();
  1094. }
  1095. void CGMagi::initObj(CRandomGenerator & rand)
  1096. {
  1097. if (ID == Obj::EYE_OF_MAGI)
  1098. {
  1099. blockVisit = true;
  1100. eyelist[subID].push_back(id);
  1101. }
  1102. }
  1103. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1104. {
  1105. if (ID == Obj::HUT_OF_MAGI)
  1106. {
  1107. h->showInfoDialog(61);
  1108. if (!eyelist[subID].empty())
  1109. {
  1110. CenterView cv;
  1111. cv.player = h->tempOwner;
  1112. cv.focusTime = 2000;
  1113. FoWChange fw;
  1114. fw.player = h->tempOwner;
  1115. fw.mode = 1;
  1116. fw.waitForDialogs = true;
  1117. for(const auto & it : eyelist[subID])
  1118. {
  1119. const CGObjectInstance *eye = cb->getObj(it);
  1120. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1121. cb->sendAndApply(&fw);
  1122. cv.pos = eye->pos;
  1123. cb->sendAndApply(&cv);
  1124. }
  1125. cv.pos = h->visitablePos();
  1126. cv.focusTime = 0;
  1127. cb->sendAndApply(&cv);
  1128. }
  1129. }
  1130. else if (ID == Obj::EYE_OF_MAGI)
  1131. {
  1132. h->showInfoDialog(48);
  1133. }
  1134. }
  1135. CGBoat::CGBoat()
  1136. {
  1137. hero = nullptr;
  1138. direction = 4;
  1139. layer = EPathfindingLayer::SAIL;
  1140. }
  1141. bool CGBoat::isCoastVisitable() const
  1142. {
  1143. return true;
  1144. }
  1145. void CGSirens::initObj(CRandomGenerator & rand)
  1146. {
  1147. blockVisit = true;
  1148. }
  1149. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1150. {
  1151. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT,ID));
  1152. }
  1153. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1154. {
  1155. InfoWindow iw;
  1156. iw.player = h->tempOwner;
  1157. if(h->hasBonusFrom(BonusSource::OBJECT,ID)) //has already visited Sirens
  1158. {
  1159. iw.type = EInfoWindowMode::AUTO;
  1160. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  1161. }
  1162. else
  1163. {
  1164. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  1165. TExpType xp = 0;
  1166. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1167. {
  1168. // 1-sized stacks are not affected by sirens
  1169. if (i->second->count == 1)
  1170. continue;
  1171. // tested H3 behavior: 30% (rounded up) of stack drowns
  1172. TQuantity drown = std::ceil(i->second->count * 0.3);
  1173. if(drown)
  1174. {
  1175. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1176. xp += drown * i->second->type->getMaxHealth();
  1177. }
  1178. }
  1179. if(xp)
  1180. {
  1181. xp = h->calculateXp(static_cast<int>(xp));
  1182. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  1183. iw.text.replaceNumber(static_cast<int>(xp));
  1184. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1185. }
  1186. else
  1187. {
  1188. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  1189. }
  1190. }
  1191. cb->showInfoDialog(&iw);
  1192. }
  1193. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1194. {
  1195. // H J L K I
  1196. // A x S x B
  1197. // C E G F D
  1198. offsets = {
  1199. {-2, 0, 0}, // A
  1200. {+2, 0, 0}, // B
  1201. {-2, 1, 0}, // C
  1202. {+2, 1, 0}, // D
  1203. {-1, 1, 0}, // E
  1204. {+1, 1, 0}, // F
  1205. {0, 1, 0}, // G
  1206. {-2, -1, 0}, // H
  1207. {+2, -1, 0}, // I
  1208. {-1, -1, 0}, // G
  1209. {+1, -1, 0}, // K
  1210. {0, -1, 0}, // L
  1211. };
  1212. }
  1213. const IObjectInterface * CGShipyard::getObject() const
  1214. {
  1215. return this;
  1216. }
  1217. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1218. {
  1219. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  1220. cb->setOwner(this, h->tempOwner);
  1221. if(shipyardStatus() != IBoatGenerator::GOOD)
  1222. {
  1223. InfoWindow iw;
  1224. iw.type = EInfoWindowMode::AUTO;
  1225. iw.player = tempOwner;
  1226. getProblemText(iw.text, h);
  1227. cb->showInfoDialog(&iw);
  1228. }
  1229. else
  1230. {
  1231. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  1232. }
  1233. }
  1234. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1235. {
  1236. serializeJsonOwner(handler);
  1237. }
  1238. BoatId CGShipyard::getBoatType() const
  1239. {
  1240. return createdBoat;
  1241. }
  1242. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1243. {
  1244. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1245. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1246. {
  1247. if (cb->getResource(h->tempOwner, EGameResID::GOLD) >= 1000) //if he can afford a map
  1248. {
  1249. //ask if he wants to buy one
  1250. int text=0;
  1251. switch (subID)
  1252. {
  1253. case 0:
  1254. text = 25;
  1255. break;
  1256. case 1:
  1257. text = 26;
  1258. break;
  1259. case 2:
  1260. text = 27;
  1261. break;
  1262. default:
  1263. logGlobal->warn("Unrecognized subtype of cartographer");
  1264. }
  1265. assert(text);
  1266. BlockingDialog bd (true, false);
  1267. bd.player = h->getOwner();
  1268. bd.text.appendLocalString (EMetaText::ADVOB_TXT, text);
  1269. cb->showBlockingDialog (&bd);
  1270. }
  1271. else //if he cannot afford
  1272. {
  1273. h->showInfoDialog(28);
  1274. }
  1275. }
  1276. else //if he already visited carographer
  1277. {
  1278. h->showInfoDialog(24);
  1279. }
  1280. }
  1281. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1282. {
  1283. if(answer) //if hero wants to buy map
  1284. {
  1285. cb->giveResource(hero->tempOwner, EGameResID::GOLD, -1000);
  1286. FoWChange fw;
  1287. fw.mode = 1;
  1288. fw.player = hero->tempOwner;
  1289. //subIDs of different types of cartographers:
  1290. //water = 0; land = 1; underground = 2;
  1291. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1292. switch(subID)
  1293. {
  1294. case 0:
  1295. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1296. break;
  1297. case 1:
  1298. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1299. break;
  1300. case 2:
  1301. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1302. break;
  1303. }
  1304. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1305. cb->sendAndApply(&fw);
  1306. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1307. }
  1308. }
  1309. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1310. {
  1311. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  1312. }
  1313. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1314. {
  1315. InfoWindow iw;
  1316. iw.type = EInfoWindowMode::AUTO;
  1317. iw.player = h->tempOwner;
  1318. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1319. assert(ts);
  1320. TeamID team = ts->id;
  1321. if(!wasVisited(team))
  1322. {
  1323. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  1324. cb->sendAndApply(&iw);
  1325. // increment general visited obelisks counter
  1326. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1327. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  1328. // mark that particular obelisk as visited for all players in the team
  1329. for(const auto & color : ts->players)
  1330. {
  1331. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1332. }
  1333. }
  1334. else
  1335. {
  1336. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  1337. cb->sendAndApply(&iw);
  1338. }
  1339. }
  1340. void CGObelisk::initObj(CRandomGenerator & rand)
  1341. {
  1342. obeliskCount++;
  1343. }
  1344. void CGObelisk::reset()
  1345. {
  1346. obeliskCount = 0;
  1347. visited.clear();
  1348. }
  1349. std::string CGObelisk::getHoverText(PlayerColor player) const
  1350. {
  1351. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1352. }
  1353. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1354. {
  1355. switch(what)
  1356. {
  1357. case CGObelisk::OBJPROP_INC:
  1358. {
  1359. auto progress = ++visited[TeamID(val)];
  1360. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1361. if(progress > obeliskCount)
  1362. {
  1363. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1364. throw std::runtime_error("internal error");
  1365. }
  1366. break;
  1367. }
  1368. default:
  1369. CTeamVisited::setPropertyDer(what, val);
  1370. break;
  1371. }
  1372. }
  1373. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1374. {
  1375. if(h->tempOwner != tempOwner)
  1376. {
  1377. PlayerColor oldOwner = tempOwner;
  1378. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1379. h->showInfoDialog(69);
  1380. giveBonusTo(h->tempOwner);
  1381. if(oldOwner.isValidPlayer()) //remove bonus from old owner
  1382. {
  1383. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1384. rb.whoID = oldOwner.getNum();
  1385. rb.source = vstd::to_underlying(BonusSource::OBJECT);
  1386. rb.id = id.getNum();
  1387. cb->sendAndApply(&rb);
  1388. }
  1389. }
  1390. }
  1391. void CGLighthouse::initObj(CRandomGenerator & rand)
  1392. {
  1393. if(tempOwner.isValidPlayer())
  1394. {
  1395. // FIXME: This is dirty hack
  1396. giveBonusTo(tempOwner, true);
  1397. }
  1398. }
  1399. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1400. {
  1401. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1402. gb.bonus.type = BonusType::MOVEMENT;
  1403. gb.bonus.val = 500;
  1404. gb.id = player.getNum();
  1405. gb.bonus.duration = BonusDuration::PERMANENT;
  1406. gb.bonus.source = BonusSource::OBJECT;
  1407. gb.bonus.sid = id.getNum();
  1408. gb.bonus.subtype = 0;
  1409. // FIXME: This is really dirty hack
  1410. // Proper fix would be to make CGLighthouse into bonus system node
  1411. // Unfortunately this will cause saves breakage
  1412. if(onInit)
  1413. gb.applyGs(cb->gameState());
  1414. else
  1415. cb->sendAndApply(&gb);
  1416. }
  1417. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1418. {
  1419. serializeJsonOwner(handler);
  1420. }
  1421. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1422. {
  1423. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1424. }
  1425. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1426. {
  1427. int32_t level = stack.type->getLevel();
  1428. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1429. int costModifier = upgradeCostPercentage[index];
  1430. if (costModifier < 0)
  1431. return; // upgrade not allowed
  1432. for(const auto & nid : stack.type->upgrades)
  1433. {
  1434. info.newID.push_back(nid);
  1435. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1436. }
  1437. }
  1438. VCMI_LIB_NAMESPACE_END