MiscObjects.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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.as<SpellID>());
  734. handler.serializeId("spell", spellId, SpellID::NONE);
  735. }
  736. }
  737. void CGSignBottle::initObj(CRandomGenerator & rand)
  738. {
  739. //if no text is set than we pick random from the predefined ones
  740. if(message.empty())
  741. {
  742. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  743. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  744. message.appendTextID(TextIdentifier("core", "randsign", messageIdentifier).get());
  745. }
  746. if(ID == Obj::OCEAN_BOTTLE)
  747. {
  748. blockVisit = true;
  749. }
  750. }
  751. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  752. {
  753. InfoWindow iw;
  754. iw.player = h->getOwner();
  755. iw.text = message;
  756. cb->showInfoDialog(&iw);
  757. if(ID == Obj::OCEAN_BOTTLE)
  758. cb->removeObject(this, h->getOwner());
  759. }
  760. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  761. {
  762. handler.serializeStruct("text", message);
  763. }
  764. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  765. {
  766. auto relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  767. if (relations == PlayerRelations::ENEMIES && stacksCount() > 0) {
  768. //TODO: Find a way to apply magic garrison effects in battle.
  769. cb->startBattleI(h, this);
  770. return;
  771. }
  772. //New owner.
  773. if (relations == PlayerRelations::ENEMIES)
  774. cb->setOwner(this, h->tempOwner);
  775. cb->showGarrisonDialog(id, h->id, removableUnits);
  776. }
  777. bool CGGarrison::passableFor(PlayerColor player) const
  778. {
  779. //FIXME: identical to same method in CGTownInstance
  780. if ( !stacksCount() )//empty - anyone can visit
  781. return true;
  782. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  783. return false;
  784. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  785. return true;
  786. return false;
  787. }
  788. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  789. {
  790. if (result.winner == 0)
  791. onHeroVisit(hero);
  792. }
  793. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  794. {
  795. handler.serializeBool("removableUnits", removableUnits);
  796. serializeJsonOwner(handler);
  797. CArmedInstance::serializeJsonOptions(handler);
  798. }
  799. void CGMagi::reset()
  800. {
  801. eyelist.clear();
  802. }
  803. void CGMagi::initObj(CRandomGenerator & rand)
  804. {
  805. if (ID == Obj::EYE_OF_MAGI)
  806. {
  807. blockVisit = true;
  808. eyelist[subID].push_back(id);
  809. }
  810. }
  811. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  812. {
  813. if (ID == Obj::HUT_OF_MAGI)
  814. {
  815. h->showInfoDialog(61);
  816. if (!eyelist[subID].empty())
  817. {
  818. CenterView cv;
  819. cv.player = h->tempOwner;
  820. cv.focusTime = 2000;
  821. FoWChange fw;
  822. fw.player = h->tempOwner;
  823. fw.mode = ETileVisibility::REVEALED;
  824. fw.waitForDialogs = true;
  825. for(const auto & it : eyelist[subID])
  826. {
  827. const CGObjectInstance *eye = cb->getObj(it);
  828. cb->getTilesInRange (fw.tiles, eye->pos, 10, ETileVisibility::HIDDEN, h->tempOwner);
  829. cb->sendAndApply(&fw);
  830. cv.pos = eye->pos;
  831. cb->sendAndApply(&cv);
  832. }
  833. cv.pos = h->visitablePos();
  834. cv.focusTime = 0;
  835. cb->sendAndApply(&cv);
  836. }
  837. }
  838. else if (ID == Obj::EYE_OF_MAGI)
  839. {
  840. h->showInfoDialog(48);
  841. }
  842. }
  843. CGBoat::CGBoat()
  844. {
  845. hero = nullptr;
  846. direction = 4;
  847. layer = EPathfindingLayer::SAIL;
  848. }
  849. bool CGBoat::isCoastVisitable() const
  850. {
  851. return true;
  852. }
  853. void CGSirens::initObj(CRandomGenerator & rand)
  854. {
  855. blockVisit = true;
  856. }
  857. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  858. {
  859. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT,ID));
  860. }
  861. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  862. {
  863. InfoWindow iw;
  864. iw.player = h->tempOwner;
  865. if(h->hasBonusFrom(BonusSource::OBJECT,ID)) //has already visited Sirens
  866. {
  867. iw.type = EInfoWindowMode::AUTO;
  868. iw.text.appendLocalString(EMetaText::ADVOB_TXT,133);
  869. }
  870. else
  871. {
  872. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  873. TExpType xp = 0;
  874. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  875. {
  876. // 1-sized stacks are not affected by sirens
  877. if (i->second->count == 1)
  878. continue;
  879. // tested H3 behavior: 30% (rounded up) of stack drowns
  880. TQuantity drown = std::ceil(i->second->count * 0.3);
  881. if(drown)
  882. {
  883. cb->changeStackCount(StackLocation(h, i->first), -drown);
  884. xp += drown * i->second->type->getMaxHealth();
  885. }
  886. }
  887. if(xp)
  888. {
  889. xp = h->calculateXp(static_cast<int>(xp));
  890. iw.text.appendLocalString(EMetaText::ADVOB_TXT,132);
  891. iw.text.replaceNumber(static_cast<int>(xp));
  892. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  893. }
  894. else
  895. {
  896. iw.text.appendLocalString(EMetaText::ADVOB_TXT,134);
  897. }
  898. }
  899. cb->showInfoDialog(&iw);
  900. }
  901. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  902. {
  903. // H J L K I
  904. // A x S x B
  905. // C E G F D
  906. offsets = {
  907. {-2, 0, 0}, // A
  908. {+2, 0, 0}, // B
  909. {-2, 1, 0}, // C
  910. {+2, 1, 0}, // D
  911. {-1, 1, 0}, // E
  912. {+1, 1, 0}, // F
  913. {0, 1, 0}, // G
  914. {-2, -1, 0}, // H
  915. {+2, -1, 0}, // I
  916. {-1, -1, 0}, // G
  917. {+1, -1, 0}, // K
  918. {0, -1, 0}, // L
  919. };
  920. }
  921. const IObjectInterface * CGShipyard::getObject() const
  922. {
  923. return this;
  924. }
  925. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  926. {
  927. if(cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner) == PlayerRelations::ENEMIES)
  928. cb->setOwner(this, h->tempOwner);
  929. if(shipyardStatus() != IBoatGenerator::GOOD)
  930. {
  931. InfoWindow iw;
  932. iw.type = EInfoWindowMode::AUTO;
  933. iw.player = tempOwner;
  934. getProblemText(iw.text, h);
  935. cb->showInfoDialog(&iw);
  936. }
  937. else
  938. {
  939. cb->showObjectWindow(this, EOpenWindowMode::SHIPYARD_WINDOW, h, false);
  940. }
  941. }
  942. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  943. {
  944. serializeJsonOwner(handler);
  945. }
  946. BoatId CGShipyard::getBoatType() const
  947. {
  948. return createdBoat;
  949. }
  950. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  951. {
  952. cb->showObjectWindow(this, EOpenWindowMode::THIEVES_GUILD, h, false);
  953. }
  954. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  955. {
  956. InfoWindow iw;
  957. iw.type = EInfoWindowMode::AUTO;
  958. iw.player = h->tempOwner;
  959. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  960. assert(ts);
  961. TeamID team = ts->id;
  962. if(!wasVisited(team))
  963. {
  964. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 96);
  965. cb->sendAndApply(&iw);
  966. // increment general visited obelisks counter
  967. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  968. cb->showObjectWindow(this, EOpenWindowMode::PUZZLE_MAP, h, false);
  969. // mark that particular obelisk as visited for all players in the team
  970. for(const auto & color : ts->players)
  971. {
  972. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  973. }
  974. }
  975. else
  976. {
  977. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 97);
  978. cb->sendAndApply(&iw);
  979. }
  980. }
  981. void CGObelisk::initObj(CRandomGenerator & rand)
  982. {
  983. obeliskCount++;
  984. }
  985. void CGObelisk::reset()
  986. {
  987. obeliskCount = 0;
  988. visited.clear();
  989. }
  990. std::string CGObelisk::getHoverText(PlayerColor player) const
  991. {
  992. return getObjectName() + " " + visitedTxt(wasVisited(player));
  993. }
  994. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  995. {
  996. switch(what)
  997. {
  998. case CGObelisk::OBJPROP_INC:
  999. {
  1000. auto progress = ++visited[TeamID(val)];
  1001. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1002. if(progress > obeliskCount)
  1003. {
  1004. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1005. throw std::runtime_error("internal error");
  1006. }
  1007. break;
  1008. }
  1009. default:
  1010. CTeamVisited::setPropertyDer(what, val);
  1011. break;
  1012. }
  1013. }
  1014. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1015. {
  1016. if(h->tempOwner != tempOwner)
  1017. {
  1018. PlayerColor oldOwner = tempOwner;
  1019. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1020. h->showInfoDialog(69);
  1021. giveBonusTo(h->tempOwner);
  1022. if(oldOwner.isValidPlayer()) //remove bonus from old owner
  1023. {
  1024. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1025. rb.whoID = oldOwner.getNum();
  1026. rb.source = vstd::to_underlying(BonusSource::OBJECT);
  1027. rb.id = id.getNum();
  1028. cb->sendAndApply(&rb);
  1029. }
  1030. }
  1031. }
  1032. void CGLighthouse::initObj(CRandomGenerator & rand)
  1033. {
  1034. if(tempOwner.isValidPlayer())
  1035. {
  1036. // FIXME: This is dirty hack
  1037. giveBonusTo(tempOwner, true);
  1038. }
  1039. }
  1040. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1041. {
  1042. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1043. gb.bonus.type = BonusType::MOVEMENT;
  1044. gb.bonus.val = 500;
  1045. gb.id = player.getNum();
  1046. gb.bonus.duration = BonusDuration::PERMANENT;
  1047. gb.bonus.source = BonusSource::OBJECT;
  1048. gb.bonus.sid = id.getNum();
  1049. gb.bonus.subtype = BonusSubtypes::heroMovementSea;
  1050. // FIXME: This is really dirty hack
  1051. // Proper fix would be to make CGLighthouse into bonus system node
  1052. // Unfortunately this will cause saves breakage
  1053. if(onInit)
  1054. gb.applyGs(cb->gameState());
  1055. else
  1056. cb->sendAndApply(&gb);
  1057. }
  1058. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1059. {
  1060. serializeJsonOwner(handler);
  1061. }
  1062. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1063. {
  1064. cb->showObjectWindow(this, EOpenWindowMode::HILL_FORT_WINDOW, h, false);
  1065. }
  1066. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1067. {
  1068. int32_t level = stack.type->getLevel();
  1069. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1070. int costModifier = upgradeCostPercentage[index];
  1071. if (costModifier < 0)
  1072. return; // upgrade not allowed
  1073. for(const auto & nid : stack.type->upgrades)
  1074. {
  1075. info.newID.push_back(nid);
  1076. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1077. }
  1078. }
  1079. VCMI_LIB_NAMESPACE_END