MiscObjects.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160
  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 "../StringConstants.h"
  13. #include "../NetPacks.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../CSoundBase.h"
  16. #include "../CConfigHandler.h"
  17. #include "../CModHandler.h"
  18. #include "../CHeroHandler.h"
  19. #include "../CSkillHandler.h"
  20. #include "CObjectClassesHandler.h"
  21. #include "../spells/CSpellHandler.h"
  22. #include "../IGameCallback.h"
  23. #include "../CGameState.h"
  24. #include "../mapping/CMap.h"
  25. #include "../CPlayerState.h"
  26. #include "../GameSettings.h"
  27. #include "../serializer/JsonSerializeFormat.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  30. ui8 CGObelisk::obeliskCount = 0; //how many obelisks are on map
  31. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  32. ///helpers
  33. static std::string visitedTxt(const bool visited)
  34. {
  35. int id = visited ? 352 : 353;
  36. return VLC->generaltexth->allTexts[id];
  37. }
  38. void CTeamVisited::setPropertyDer(ui8 what, ui32 val)
  39. {
  40. if(what == CTeamVisited::OBJPROP_VISITED)
  41. players.insert(PlayerColor(val));
  42. }
  43. bool CTeamVisited::wasVisited(PlayerColor player) const
  44. {
  45. return wasVisited(cb->getPlayerState(player)->team);
  46. }
  47. bool CTeamVisited::wasVisited(const CGHeroInstance * h) const
  48. {
  49. return wasVisited(h->tempOwner);
  50. }
  51. bool CTeamVisited::wasVisited(const TeamID & team) const
  52. {
  53. for(const auto & i : players)
  54. {
  55. if(cb->getPlayerState(i)->team == team)
  56. return true;
  57. }
  58. return false;
  59. }
  60. std::string CGCreature::getHoverText(PlayerColor player) const
  61. {
  62. if(stacks.empty())
  63. {
  64. //should not happen...
  65. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", pos.toString(), subID, id.getNum());
  66. return "INVALID_STACK";
  67. }
  68. std::string hoverName;
  69. MetaString ms;
  70. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  71. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  72. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  73. ms << CCreature::getQuantityRangeStringForId(monsterQuantityId);
  74. else
  75. ms.addTxt(MetaString::ARRAY_TXT, quantityTextIndex);
  76. ms << " " ;
  77. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  78. ms.toString(hoverName);
  79. return hoverName;
  80. }
  81. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  82. {
  83. std::string hoverName;
  84. if(hero->hasVisions(this, 0))
  85. {
  86. MetaString ms;
  87. ms << stacks.begin()->second->count;
  88. ms << " " ;
  89. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  90. ms << "\n";
  91. int decision = takenAction(hero, true);
  92. switch (decision)
  93. {
  94. case FIGHT:
  95. ms.addTxt(MetaString::GENERAL_TXT,246);
  96. break;
  97. case FLEE:
  98. ms.addTxt(MetaString::GENERAL_TXT,245);
  99. break;
  100. case JOIN_FOR_FREE:
  101. ms.addTxt(MetaString::GENERAL_TXT,243);
  102. break;
  103. default: //decision = cost in gold
  104. ms << boost::to_string(boost::format(VLC->generaltexth->allTexts[244]) % decision);
  105. break;
  106. }
  107. ms.toString(hoverName);
  108. }
  109. else
  110. {
  111. hoverName = getHoverText(hero->tempOwner);
  112. }
  113. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  114. int choice;
  115. double ratio = (static_cast<double>(getArmyStrength()) / hero->getTotalStrength());
  116. if (ratio < 0.1) choice = 0;
  117. else if (ratio < 0.25) choice = 1;
  118. else if (ratio < 0.6) choice = 2;
  119. else if (ratio < 0.9) choice = 3;
  120. else if (ratio < 1.1) choice = 4;
  121. else if (ratio < 1.3) choice = 5;
  122. else if (ratio < 1.8) choice = 6;
  123. else if (ratio < 2.5) choice = 7;
  124. else if (ratio < 4) choice = 8;
  125. else if (ratio < 8) choice = 9;
  126. else if (ratio < 20) choice = 10;
  127. else choice = 11;
  128. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  129. return hoverName;
  130. }
  131. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  132. {
  133. int action = takenAction(h);
  134. switch( action ) //decide what we do...
  135. {
  136. case FIGHT:
  137. fight(h);
  138. break;
  139. case FLEE:
  140. {
  141. flee(h);
  142. break;
  143. }
  144. case JOIN_FOR_FREE: //join for free
  145. {
  146. BlockingDialog ynd(true,false);
  147. ynd.player = h->tempOwner;
  148. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  149. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  150. cb->showBlockingDialog(&ynd);
  151. break;
  152. }
  153. default: //join for gold
  154. {
  155. assert(action > 0);
  156. //ask if player agrees to pay gold
  157. BlockingDialog ynd(true,false);
  158. ynd.player = h->tempOwner;
  159. std::string tmp = VLC->generaltexth->advobtxt[90];
  160. boost::algorithm::replace_first(tmp, "%d", std::to_string(getStackCount(SlotID(0))));
  161. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  162. boost::algorithm::replace_first(tmp,"%s",VLC->creh->objects[subID]->getNamePluralTranslated());
  163. ynd.text << tmp;
  164. cb->showBlockingDialog(&ynd);
  165. break;
  166. }
  167. }
  168. }
  169. void CGCreature::initObj(CRandomGenerator & rand)
  170. {
  171. blockVisit = true;
  172. switch(character)
  173. {
  174. case 0:
  175. character = -4;
  176. break;
  177. case 1:
  178. character = rand.nextInt(1, 7);
  179. break;
  180. case 2:
  181. character = rand.nextInt(1, 10);
  182. break;
  183. case 3:
  184. character = rand.nextInt(4, 10);
  185. break;
  186. case 4:
  187. character = 10;
  188. break;
  189. }
  190. stacks[SlotID(0)]->setType(CreatureID(subID));
  191. TQuantity &amount = stacks[SlotID(0)]->count;
  192. CCreature &c = *VLC->creh->objects[subID];
  193. if(amount == 0)
  194. {
  195. amount = rand.nextInt(c.ammMin, c.ammMax);
  196. if(amount == 0) //armies with 0 creatures are illegal
  197. {
  198. logGlobal->warn("Stack %s cannot have 0 creatures. Check properties of %s", nodeName(), c.nodeName());
  199. amount = 1;
  200. }
  201. }
  202. temppower = stacks[SlotID(0)]->count * static_cast<ui64>(1000);
  203. refusedJoining = false;
  204. }
  205. void CGCreature::newTurn(CRandomGenerator & rand) const
  206. {//Works only for stacks of single type of size up to 2 millions
  207. if (!notGrowingTeam)
  208. {
  209. if (stacks.begin()->second->count < VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  210. {
  211. ui32 power = static_cast<ui32>(temppower * (100 + VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  212. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  213. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  214. }
  215. }
  216. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  217. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->settings()->getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  218. }
  219. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  220. {
  221. switch (what)
  222. {
  223. case ObjProperty::MONSTER_COUNT:
  224. stacks[SlotID(0)]->count = val;
  225. break;
  226. case ObjProperty::MONSTER_POWER:
  227. temppower = val;
  228. break;
  229. case ObjProperty::MONSTER_EXP:
  230. giveStackExp(val);
  231. break;
  232. case ObjProperty::MONSTER_RESTORE_TYPE:
  233. formation.basicType = val;
  234. break;
  235. case ObjProperty::MONSTER_REFUSED_JOIN:
  236. refusedJoining = val;
  237. break;
  238. }
  239. }
  240. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  241. {
  242. //calculate relative strength of hero and creatures armies
  243. double relStrength = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  244. int powerFactor;
  245. if(relStrength >= 7)
  246. powerFactor = 11;
  247. else if(relStrength >= 1)
  248. powerFactor = static_cast<int>(2 * (relStrength - 1));
  249. else if(relStrength >= 0.5)
  250. powerFactor = -1;
  251. else if(relStrength >= 0.333)
  252. powerFactor = -2;
  253. else
  254. powerFactor = -3;
  255. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  256. const CCreature * myCreature = VLC->creh->objects[subID];
  257. myKindCres.insert(myCreature->getId()); //we
  258. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  259. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->objects)
  260. {
  261. if(vstd::contains(crea->upgrades, myCreature->getId())) //it's our base creatures
  262. myKindCres.insert(crea->getId());
  263. }
  264. int count = 0; //how many creatures of similar kind has hero
  265. int totalCount = 0;
  266. for(const auto & elem : h->Slots())
  267. {
  268. if(vstd::contains(myKindCres,elem.second->type->getId()))
  269. count += elem.second->count;
  270. totalCount += elem.second->count;
  271. }
  272. int sympathy = 0; // 0 if hero have no similar creatures
  273. if(count)
  274. sympathy++; // 1 - if hero have at least 1 similar creature
  275. if(count*2 > totalCount)
  276. sympathy++; // 2 - hero have similar creatures more that 50%
  277. int diplomacy = h->valOfBonuses(Bonus::WANDERING_CREATURES_JOIN_BONUS);
  278. int charisma = powerFactor + diplomacy + sympathy;
  279. if(charisma < character)
  280. return FIGHT;
  281. if (allowJoin)
  282. {
  283. if(diplomacy + sympathy + 1 >= character)
  284. return JOIN_FOR_FREE;
  285. else if(diplomacy * 2 + sympathy + 1 >= character)
  286. return VLC->creatures()->getByIndex(subID)->getRecruitCost(EGameResID::GOLD) * getStackCount(SlotID(0)); //join for gold
  287. }
  288. //we are still here - creatures have not joined hero, flee or fight
  289. if (charisma > character && !neverFlees)
  290. return FLEE;
  291. else
  292. return FIGHT;
  293. }
  294. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  295. {
  296. if(refusedJoining)
  297. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  298. if(pursue)
  299. {
  300. fight(h);
  301. }
  302. else
  303. {
  304. cb->removeObject(this);
  305. }
  306. }
  307. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  308. {
  309. if(!accept)
  310. {
  311. if(takenAction(h,false) == FLEE)
  312. {
  313. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  314. flee(h);
  315. }
  316. else //they fight
  317. {
  318. h->showInfoDialog(87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  319. fight(h);
  320. }
  321. }
  322. else //accepted
  323. {
  324. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  325. {
  326. InfoWindow iw;
  327. iw.player = h->tempOwner;
  328. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  329. cb->showInfoDialog(&iw);
  330. //act as if player refused
  331. joinDecision(h,cost,false);
  332. return;
  333. }
  334. //take gold
  335. if(cost)
  336. cb->giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  337. giveReward(h);
  338. cb->tryJoiningArmy(this, h, true, true);
  339. }
  340. }
  341. void CGCreature::fight( const CGHeroInstance *h ) const
  342. {
  343. //split stacks
  344. //TODO: multiple creature types in a stack?
  345. int basicType = stacks.begin()->second->type->getId();
  346. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  347. int stacksCount = getNumberOfStacks(h);
  348. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  349. int amount = getStackCount(SlotID(0));
  350. int m = amount / stacksCount;
  351. int b = stacksCount * (m + 1) - amount;
  352. int a = stacksCount - b;
  353. SlotID sourceSlot = stacks.begin()->first;
  354. for (int slotID = 1; slotID < a; ++slotID)
  355. {
  356. int stackSize = m + 1;
  357. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  358. }
  359. for (int slotID = a; slotID < stacksCount; ++slotID)
  360. {
  361. int stackSize = m;
  362. if (slotID) //don't do this when a = 0 -> stack is single
  363. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  364. }
  365. if (stacksCount > 1)
  366. {
  367. if (containsUpgradedStack()) //upgrade
  368. {
  369. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  370. const auto & upgrades = getStack(slotID).type->upgrades;
  371. if(!upgrades.empty())
  372. {
  373. auto it = RandomGeneratorUtil::nextItem(upgrades, CRandomGenerator::getDefault());
  374. cb->changeStackType(StackLocation(this, slotID), VLC->creh->objects[*it]);
  375. }
  376. }
  377. }
  378. cb->startBattleI(h, this);
  379. }
  380. void CGCreature::flee( const CGHeroInstance * h ) const
  381. {
  382. BlockingDialog ynd(true,false);
  383. ynd.player = h->tempOwner;
  384. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  385. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  386. cb->showBlockingDialog(&ynd);
  387. }
  388. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  389. {
  390. if(result.winner == 0)
  391. {
  392. giveReward(hero);
  393. cb->removeObject(this);
  394. }
  395. else if(result.winner > 1) // draw
  396. {
  397. // guarded reward is lost forever on draw
  398. cb->removeObject(this);
  399. }
  400. else
  401. {
  402. //merge stacks into one
  403. TSlots::const_iterator i;
  404. CCreature * cre = VLC->creh->objects[formation.basicType];
  405. for(i = stacks.begin(); i != stacks.end(); i++)
  406. {
  407. if(cre->isMyUpgrade(i->second->type))
  408. {
  409. cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures
  410. }
  411. }
  412. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  413. if(!hasStackAtSlot(SlotID(0)))
  414. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  415. while(stacks.size() > 1) //hopefully that's enough
  416. {
  417. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  418. i = stacks.end();
  419. i--;
  420. SlotID slot = getSlotFor(i->second->type);
  421. if(slot == i->first) //no reason to move stack to its own slot
  422. break;
  423. else
  424. cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  425. }
  426. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  427. }
  428. }
  429. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  430. {
  431. auto action = takenAction(hero);
  432. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  433. joinDecision(hero, action, answer);
  434. else if(action != FIGHT)
  435. fleeDecision(hero, answer);
  436. else
  437. assert(0);
  438. }
  439. bool CGCreature::containsUpgradedStack() const
  440. {
  441. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  442. float a = 2992.911117f;
  443. float b = 14174.264968f;
  444. float c = 5325.181015f;
  445. float d = 32788.727920f;
  446. int val = static_cast<int>(std::floor(a * pos.x + b * pos.y + c * pos.z + d));
  447. return ((val % 32768) % 100) < 50;
  448. }
  449. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  450. {
  451. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  452. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  453. int split = 1;
  454. if (strengthRatio < 0.5f)
  455. split = 7;
  456. else if (strengthRatio < 0.67f)
  457. split = 6;
  458. else if (strengthRatio < 1)
  459. split = 5;
  460. else if (strengthRatio < 1.5f)
  461. split = 4;
  462. else if (strengthRatio < 2)
  463. split = 3;
  464. else
  465. split = 2;
  466. ui32 a = 1550811371u;
  467. ui32 b = 3359066809u;
  468. ui32 c = 1943276003u;
  469. ui32 d = 3174620878u;
  470. ui32 R1 = a * static_cast<ui32>(pos.x) + b * static_cast<ui32>(pos.y) + c * static_cast<ui32>(pos.z) + d;
  471. ui32 R2 = (R1 >> 16) & 0x7fff;
  472. int R4 = R2 % 100 + 1;
  473. if (R4 <= 20)
  474. split -= 1;
  475. else if (R4 >= 80)
  476. split += 1;
  477. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  478. vstd::amin(split, 7); //can't have more than 7 stacks
  479. return split;
  480. }
  481. void CGCreature::giveReward(const CGHeroInstance * h) const
  482. {
  483. InfoWindow iw;
  484. iw.player = h->tempOwner;
  485. if(!resources.empty())
  486. {
  487. cb->giveResources(h->tempOwner, resources);
  488. for(int i = 0; i < resources.size(); i++)
  489. {
  490. if(resources[i] > 0)
  491. iw.components.emplace_back(Component::EComponentType::RESOURCE, i, resources[i], 0);
  492. }
  493. }
  494. if(gainedArtifact != ArtifactID::NONE)
  495. {
  496. cb->giveHeroNewArtifact(h, VLC->arth->objects[gainedArtifact], ArtifactPosition::FIRST_AVAILABLE);
  497. iw.components.emplace_back(Component::EComponentType::ARTIFACT, gainedArtifact, 0, 0);
  498. }
  499. if(!iw.components.empty())
  500. {
  501. iw.type = EInfoWindowMode::AUTO;
  502. iw.text.addTxt(MetaString::ADVOB_TXT, 183); // % has found treasure
  503. iw.text.addReplacement(h->getNameTranslated());
  504. cb->showInfoDialog(&iw);
  505. }
  506. }
  507. static const std::vector<std::string> CHARACTER_JSON =
  508. {
  509. "compliant", "friendly", "aggressive", "hostile", "savage"
  510. };
  511. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  512. {
  513. handler.serializeEnum("character", character, CHARACTER_JSON);
  514. if(handler.saving)
  515. {
  516. if(hasStackAtSlot(SlotID(0)))
  517. {
  518. si32 amount = getStack(SlotID(0)).count;
  519. handler.serializeInt("amount", amount, 0);
  520. }
  521. }
  522. else
  523. {
  524. si32 amount = 0;
  525. handler.serializeInt("amount", amount);
  526. auto * hlp = new CStackInstance();
  527. hlp->count = amount;
  528. //type will be set during initialization
  529. putStack(SlotID(0), hlp);
  530. }
  531. resources.serializeJson(handler, "rewardResources");
  532. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  533. handler.serializeBool("noGrowing", notGrowingTeam);
  534. handler.serializeBool("neverFlees", neverFlees);
  535. handler.serializeString("rewardMessage", message);
  536. }
  537. //CGMine
  538. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  539. {
  540. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  541. if(relations == 2) //we're visiting our mine
  542. {
  543. cb->showGarrisonDialog(id,h->id,true);
  544. return;
  545. }
  546. else if (relations == 1)//ally
  547. return;
  548. if(stacksCount()) //Mine is guarded
  549. {
  550. BlockingDialog ynd(true,false);
  551. ynd.player = h->tempOwner;
  552. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  553. cb->showBlockingDialog(&ynd);
  554. return;
  555. }
  556. flagMine(h->tempOwner);
  557. }
  558. void CGMine::newTurn(CRandomGenerator & rand) const
  559. {
  560. if(cb->getDate() == 1)
  561. return;
  562. if (tempOwner == PlayerColor::NEUTRAL)
  563. return;
  564. cb->giveResource(tempOwner, producedResource, producedQuantity);
  565. }
  566. void CGMine::initObj(CRandomGenerator & rand)
  567. {
  568. if(isAbandoned())
  569. {
  570. //set guardians
  571. int howManyTroglodytes = rand.nextInt(100, 199);
  572. auto * troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  573. putStack(SlotID(0), troglodytes);
  574. assert(!abandonedMineResources.empty());
  575. producedResource = *RandomGeneratorUtil::nextItem(abandonedMineResources, rand);
  576. }
  577. else
  578. {
  579. producedResource = GameResID(subID);
  580. }
  581. producedQuantity = defaultResProduction();
  582. }
  583. bool CGMine::isAbandoned() const
  584. {
  585. return (subID >= 7);
  586. }
  587. std::string CGMine::getObjectName() const
  588. {
  589. return VLC->generaltexth->translate("core.minename", subID);
  590. }
  591. std::string CGMine::getHoverText(PlayerColor player) const
  592. {
  593. std::string hoverName = CArmedInstance::getHoverText(player);
  594. if (tempOwner != PlayerColor::NEUTRAL)
  595. hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")";
  596. if(stacksCount())
  597. {
  598. hoverName += "\n";
  599. hoverName += VLC->generaltexth->allTexts[202]; //Guarded by
  600. hoverName += " ";
  601. hoverName += getArmyDescription();
  602. }
  603. return hoverName;
  604. }
  605. void CGMine::flagMine(const PlayerColor & player) const
  606. {
  607. assert(tempOwner != player);
  608. cb->setOwner(this, player); //not ours? flag it!
  609. InfoWindow iw;
  610. iw.type = EInfoWindowMode::AUTO;
  611. iw.soundID = soundBase::FLAGMINE;
  612. iw.text.addTxt(MetaString::MINE_EVNTS, producedResource); //not use subID, abandoned mines uses default mine texts
  613. iw.player = player;
  614. iw.components.emplace_back(Component::EComponentType::RESOURCE, producedResource, producedQuantity, -1);
  615. cb->showInfoDialog(&iw);
  616. }
  617. ui32 CGMine::defaultResProduction() const
  618. {
  619. switch(producedResource.toEnum())
  620. {
  621. case EGameResID::WOOD:
  622. case EGameResID::ORE:
  623. return 2;
  624. case EGameResID::GOLD:
  625. return 1000;
  626. default:
  627. return 1;
  628. }
  629. }
  630. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  631. {
  632. if(result.winner == 0) //attacker won
  633. {
  634. if(isAbandoned())
  635. {
  636. hero->showInfoDialog(85);
  637. }
  638. flagMine(hero->tempOwner);
  639. }
  640. }
  641. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  642. {
  643. if(answer)
  644. cb->startBattleI(hero, this);
  645. }
  646. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  647. {
  648. CCreatureSet::serializeJson(handler, "army", 7);
  649. if(isAbandoned())
  650. {
  651. if(handler.saving)
  652. {
  653. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  654. for(auto const & resID : abandonedMineResources)
  655. {
  656. JsonNode one(JsonNode::JsonType::DATA_STRING);
  657. one.String() = GameConstants::RESOURCE_NAMES[resID];
  658. node.Vector().push_back(one);
  659. }
  660. handler.serializeRaw("possibleResources", node, boost::none);
  661. }
  662. else
  663. {
  664. auto guard = handler.enterArray("possibleResources");
  665. const JsonNode & node = handler.getCurrent();
  666. std::set<int> abandonedMineResources;
  667. auto names = node.convertTo<std::vector<std::string>>();
  668. for(const std::string & s : names)
  669. {
  670. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  671. if(raw_res < 0)
  672. logGlobal->error("Invalid resource name: %s", s);
  673. else
  674. abandonedMineResources.insert(raw_res);
  675. }
  676. }
  677. }
  678. else
  679. {
  680. serializeJsonOwner(handler);
  681. }
  682. }
  683. std::string CGResource::getHoverText(PlayerColor player) const
  684. {
  685. return VLC->generaltexth->restypes[subID];
  686. }
  687. void CGResource::initObj(CRandomGenerator & rand)
  688. {
  689. blockVisit = true;
  690. if(amount == CGResource::RANDOM_AMOUNT)
  691. {
  692. switch(static_cast<EGameResID>(subID))
  693. {
  694. case EGameResID::GOLD:
  695. amount = rand.nextInt(5, 10) * 100;
  696. break;
  697. case EGameResID::WOOD: case EGameResID::ORE:
  698. amount = rand.nextInt(6, 10);
  699. break;
  700. default:
  701. amount = rand.nextInt(3, 5);
  702. break;
  703. }
  704. }
  705. }
  706. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  707. {
  708. if(stacksCount())
  709. {
  710. if(!message.empty())
  711. {
  712. BlockingDialog ynd(true,false);
  713. ynd.player = h->getOwner();
  714. ynd.text << message;
  715. cb->showBlockingDialog(&ynd);
  716. }
  717. else
  718. {
  719. blockingDialogAnswered(h, true); //behave as if player accepted battle
  720. }
  721. }
  722. else
  723. collectRes(h->getOwner());
  724. }
  725. void CGResource::collectRes(const PlayerColor & player) const
  726. {
  727. cb->giveResource(player, static_cast<EGameResID>(subID), amount);
  728. InfoWindow sii;
  729. sii.player = player;
  730. if(!message.empty())
  731. {
  732. sii.type = EInfoWindowMode::AUTO;
  733. sii.text << message;
  734. }
  735. else
  736. {
  737. sii.type = EInfoWindowMode::INFO;
  738. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  739. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  740. }
  741. sii.components.emplace_back(Component::EComponentType::RESOURCE,subID,amount,0);
  742. sii.soundID = soundBase::pickup01 + CRandomGenerator::getDefault().nextInt(6);
  743. cb->showInfoDialog(&sii);
  744. cb->removeObject(this);
  745. }
  746. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  747. {
  748. if(result.winner == 0) //attacker won
  749. collectRes(hero->getOwner());
  750. }
  751. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  752. {
  753. if(answer)
  754. cb->startBattleI(hero, this);
  755. }
  756. void CGResource::serializeJsonOptions(JsonSerializeFormat & handler)
  757. {
  758. CCreatureSet::serializeJson(handler, "guards", 7);
  759. handler.serializeInt("amount", amount, 0);
  760. handler.serializeString("guardMessage", message);
  761. }
  762. bool CGTeleport::isEntrance() const
  763. {
  764. return type == BOTH || type == ENTRANCE;
  765. }
  766. bool CGTeleport::isExit() const
  767. {
  768. return type == BOTH || type == EXIT;
  769. }
  770. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  771. {
  772. return vstd::contains(getAllEntrances(), id);
  773. }
  774. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  775. {
  776. return vstd::contains(getAllExits(), id);
  777. }
  778. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  779. {
  780. auto ret = cb->getTeleportChannelEntraces(channel);
  781. if(excludeCurrent)
  782. vstd::erase_if_present(ret, id);
  783. return ret;
  784. }
  785. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  786. {
  787. auto ret = cb->getTeleportChannelExits(channel);
  788. if(excludeCurrent)
  789. vstd::erase_if_present(ret, id);
  790. return ret;
  791. }
  792. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  793. {
  794. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  795. if(!passableExits.empty())
  796. return *RandomGeneratorUtil::nextItem(passableExits, CRandomGenerator::getDefault());
  797. return ObjectInstanceID();
  798. }
  799. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  800. {
  801. return ((dynamic_cast<const CGTeleport *>(obj)));
  802. }
  803. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  804. {
  805. return src && dst && src->isChannelExit(dst->id);
  806. }
  807. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  808. {
  809. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  810. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  811. return isConnected(srcObj, dstObj);
  812. }
  813. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  814. {
  815. auto * objTopVisObj = gs->map->getTile(obj->visitablePos()).topVisitableObj();
  816. if(objTopVisObj->ID == Obj::HERO)
  817. {
  818. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  819. return false;
  820. // Check if it's friendly hero or not
  821. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  822. {
  823. // Exchange between heroes only possible via subterranean gates
  824. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  825. return false;
  826. }
  827. }
  828. return true;
  829. }
  830. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  831. {
  832. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  833. {
  834. return !isExitPassable(gs, h, gs->getObj(exit));
  835. });
  836. return exits;
  837. }
  838. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  839. {
  840. std::shared_ptr<TeleportChannel> tc;
  841. if(channelsList.find(obj->channel) == channelsList.end())
  842. {
  843. tc = std::make_shared<TeleportChannel>();
  844. channelsList.insert(std::make_pair(obj->channel, tc));
  845. }
  846. else
  847. tc = channelsList[obj->channel];
  848. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  849. tc->entrances.push_back(obj->id);
  850. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  851. tc->exits.push_back(obj->id);
  852. if(!tc->entrances.empty() && !tc->exits.empty()
  853. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  854. {
  855. tc->passability = TeleportChannel::PASSABLE;
  856. }
  857. }
  858. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, int SubID) const
  859. {
  860. for(auto obj : cb->gameState()->map->objects)
  861. {
  862. if(!obj)
  863. continue;
  864. const auto * teleportObj = dynamic_cast<const CGTeleport *>(cb->getObj(obj->id));
  865. if(teleportObj && vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  866. return teleportObj->channel;
  867. }
  868. return TeleportChannelID();
  869. }
  870. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  871. {
  872. TeleportDialog td(h->tempOwner, channel);
  873. if(isEntrance())
  874. {
  875. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  876. {
  877. auto exits = cb->getTeleportChannelExits(channel);
  878. for(const auto & exit : exits)
  879. {
  880. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  881. }
  882. }
  883. if(cb->isTeleportChannelImpassable(channel))
  884. {
  885. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), pos.toString());
  886. td.impassable = true;
  887. }
  888. else if(getRandomExit(h) == ObjectInstanceID())
  889. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), pos.toString());
  890. }
  891. else
  892. h->showInfoDialog(70);
  893. cb->showTeleportDialog(&td);
  894. }
  895. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  896. {
  897. int3 dPos;
  898. auto randomExit = getRandomExit(hero);
  899. auto realExits = getAllExits(true);
  900. if(!isEntrance() // Do nothing if hero visited exit only object
  901. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  902. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  903. {
  904. return;
  905. }
  906. else if(vstd::isValidIndex(exits, answer))
  907. dPos = exits[answer].second;
  908. else
  909. dPos = hero->convertFromVisitablePos(cb->getObj(randomExit)->visitablePos());
  910. cb->moveHero(hero->id, dPos, true);
  911. }
  912. void CGMonolith::initObj(CRandomGenerator & rand)
  913. {
  914. std::vector<Obj> IDs;
  915. IDs.push_back(ID);
  916. switch(ID)
  917. {
  918. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  919. type = ENTRANCE;
  920. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  921. break;
  922. case Obj::MONOLITH_ONE_WAY_EXIT:
  923. type = EXIT;
  924. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  925. break;
  926. case Obj::MONOLITH_TWO_WAY:
  927. default:
  928. type = BOTH;
  929. break;
  930. }
  931. channel = findMeChannel(IDs, subID);
  932. if(channel == TeleportChannelID())
  933. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  934. addToChannel(cb->gameState()->map->teleportChannels, this);
  935. }
  936. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  937. {
  938. TeleportDialog td(h->tempOwner, channel);
  939. if(cb->isTeleportChannelImpassable(channel))
  940. {
  941. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  942. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), pos.toString());
  943. td.impassable = true;
  944. }
  945. else
  946. {
  947. auto exit = getRandomExit(h);
  948. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  949. }
  950. cb->showTeleportDialog(&td);
  951. }
  952. void CGSubterraneanGate::initObj(CRandomGenerator & rand)
  953. {
  954. type = BOTH;
  955. }
  956. void CGSubterraneanGate::postInit() //matches subterranean gates into pairs
  957. {
  958. //split on underground and surface gates
  959. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  960. for(auto & obj : cb->gameState()->map->objects)
  961. {
  962. if(!obj) // FIXME: Find out why there are nullptr objects right after initialization
  963. continue;
  964. auto * hlp = dynamic_cast<CGSubterraneanGate *>(cb->gameState()->getObjInstance(obj->id));
  965. if(hlp)
  966. gatesSplit[hlp->pos.z].push_back(hlp);
  967. }
  968. //sort by position
  969. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  970. {
  971. return a->pos < b->pos;
  972. });
  973. auto assignToChannel = [&](CGSubterraneanGate * obj)
  974. {
  975. if(obj->channel == TeleportChannelID())
  976. { // if object not linked to channel then create new channel
  977. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  978. addToChannel(cb->gameState()->map->teleportChannels, obj);
  979. }
  980. };
  981. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  982. {
  983. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  984. //find nearest underground exit
  985. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  986. for(int j = 0; j < gatesSplit[1].size(); j++)
  987. {
  988. CGSubterraneanGate *checked = gatesSplit[1][j];
  989. if(checked->channel != TeleportChannelID())
  990. continue;
  991. si32 hlp = checked->pos.dist2dSQ(objCurrent->pos);
  992. if(hlp < best.second)
  993. {
  994. best.first = j;
  995. best.second = hlp;
  996. }
  997. }
  998. assignToChannel(objCurrent);
  999. if(best.first >= 0) //found pair
  1000. {
  1001. gatesSplit[1][best.first]->channel = objCurrent->channel;
  1002. addToChannel(cb->gameState()->map->teleportChannels, gatesSplit[1][best.first]);
  1003. }
  1004. }
  1005. // we should assign empty channels to underground gates if they don't have matching overground gates
  1006. for(auto & i : gatesSplit[1])
  1007. assignToChannel(i);
  1008. }
  1009. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  1010. {
  1011. TeleportDialog td(h->tempOwner, channel);
  1012. if(cb->isTeleportChannelImpassable(channel))
  1013. {
  1014. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), pos.toString());
  1015. td.impassable = true;
  1016. }
  1017. else if(getRandomExit(h) == ObjectInstanceID())
  1018. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), pos.toString());
  1019. if(!isProtected(h))
  1020. {
  1021. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  1022. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  1023. {
  1024. if(h->getPower(targetstack) > h->getPower(i->first))
  1025. targetstack = (i->first);
  1026. }
  1027. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  1028. vstd::amax(countToTake, 1);
  1029. InfoWindow iw;
  1030. iw.type = EInfoWindowMode::AUTO;
  1031. iw.player = h->tempOwner;
  1032. iw.text.addTxt(MetaString::ADVOB_TXT, 168);
  1033. iw.components.emplace_back(CStackBasicDescriptor(h->getCreature(targetstack), -countToTake));
  1034. cb->showInfoDialog(&iw);
  1035. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  1036. }
  1037. else
  1038. {
  1039. auto exits = getAllExits();
  1040. for(const auto & exit : exits)
  1041. {
  1042. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  1043. for(const auto & bPos : blockedPosList)
  1044. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(bPos)));
  1045. }
  1046. }
  1047. cb->showTeleportDialog(&td);
  1048. }
  1049. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  1050. {
  1051. int3 dPos;
  1052. auto realExits = getAllExits();
  1053. if(exits.empty() && realExits.empty())
  1054. return;
  1055. else if(vstd::isValidIndex(exits, answer))
  1056. dPos = exits[answer].second;
  1057. else
  1058. {
  1059. auto exit = getRandomExit(hero);
  1060. if(exit == ObjectInstanceID())
  1061. return;
  1062. const auto * obj = cb->getObj(exit);
  1063. std::set<int3> tiles = obj->getBlockedPos();
  1064. dPos = hero->convertFromVisitablePos(*RandomGeneratorUtil::nextItem(tiles, CRandomGenerator::getDefault()));
  1065. }
  1066. cb->moveHero(hero->id, dPos, true);
  1067. }
  1068. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  1069. {
  1070. return h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION)
  1071. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1);
  1072. }
  1073. void CGArtifact::initObj(CRandomGenerator & rand)
  1074. {
  1075. blockVisit = true;
  1076. if(ID == Obj::ARTIFACT)
  1077. {
  1078. if (!storedArtifact)
  1079. {
  1080. auto * a = new CArtifactInstance();
  1081. cb->gameState()->map->addNewArtifactInstance(a);
  1082. storedArtifact = a;
  1083. }
  1084. if(!storedArtifact->artType)
  1085. storedArtifact->setType(VLC->arth->objects[subID]);
  1086. }
  1087. if(ID == Obj::SPELL_SCROLL)
  1088. subID = 1;
  1089. assert(storedArtifact->artType);
  1090. assert(storedArtifact->getParentNodes().size());
  1091. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  1092. }
  1093. std::string CGArtifact::getObjectName() const
  1094. {
  1095. return VLC->artifacts()->getByIndex(subID)->getNameTranslated();
  1096. }
  1097. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  1098. {
  1099. if(!stacksCount())
  1100. {
  1101. InfoWindow iw;
  1102. iw.type = EInfoWindowMode::AUTO;
  1103. iw.player = h->tempOwner;
  1104. if(storedArtifact->artType->canBePutAt(h))
  1105. {
  1106. switch (ID)
  1107. {
  1108. case Obj::ARTIFACT:
  1109. {
  1110. iw.components.emplace_back(Component::EComponentType::ARTIFACT, subID, 0, 0);
  1111. if(message.length())
  1112. iw.text << message;
  1113. else
  1114. iw.text.addTxt(MetaString::ART_EVNTS, subID);
  1115. }
  1116. break;
  1117. case Obj::SPELL_SCROLL:
  1118. {
  1119. int spellID = storedArtifact->getGivenSpellID();
  1120. iw.components.emplace_back(Component::EComponentType::SPELL, spellID, 0, 0);
  1121. if(message.length())
  1122. iw.text << message;
  1123. else
  1124. {
  1125. iw.text.addTxt(MetaString::ADVOB_TXT,135);
  1126. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  1127. }
  1128. }
  1129. break;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. iw.text.addTxt(MetaString::ADVOB_TXT, 2);
  1135. }
  1136. cb->showInfoDialog(&iw);
  1137. pick(h);
  1138. }
  1139. else
  1140. {
  1141. switch(ID)
  1142. {
  1143. case Obj::ARTIFACT:
  1144. {
  1145. BlockingDialog ynd(true,false);
  1146. ynd.player = h->getOwner();
  1147. if(message.length())
  1148. ynd.text << message;
  1149. else
  1150. {
  1151. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  1152. ynd.text.addTxt(MetaString::GENERAL_TXT, 420);
  1153. ynd.text.addReplacement("");
  1154. ynd.text.addReplacement(getArmyDescription());
  1155. ynd.text.addReplacement(MetaString::GENERAL_TXT, 43); // creatures
  1156. }
  1157. cb->showBlockingDialog(&ynd);
  1158. }
  1159. break;
  1160. case Obj::SPELL_SCROLL:
  1161. {
  1162. if(message.length())
  1163. {
  1164. BlockingDialog ynd(true,false);
  1165. ynd.player = h->getOwner();
  1166. ynd.text << message;
  1167. cb->showBlockingDialog(&ynd);
  1168. }
  1169. else
  1170. blockingDialogAnswered(h, true);
  1171. }
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. void CGArtifact::pick(const CGHeroInstance * h) const
  1177. {
  1178. if(cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE))
  1179. cb->removeObject(this);
  1180. }
  1181. BattleField CGArtifact::getBattlefield() const
  1182. {
  1183. return BattleField::NONE;
  1184. }
  1185. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1186. {
  1187. if(result.winner == 0) //attacker won
  1188. pick(hero);
  1189. }
  1190. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1191. {
  1192. if(answer)
  1193. cb->startBattleI(hero, this);
  1194. }
  1195. void CGArtifact::afterAddToMap(CMap * map)
  1196. {
  1197. //Artifacts from map objects are never removed
  1198. //FIXME: This should be revertible in map editor
  1199. if(ID == Obj::SPELL_SCROLL && storedArtifact && storedArtifact->id.getNum() < 0)
  1200. map->addNewArtifactInstance(storedArtifact);
  1201. }
  1202. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  1203. {
  1204. handler.serializeString("guardMessage", message);
  1205. CCreatureSet::serializeJson(handler, "guards" ,7);
  1206. if(handler.saving && ID == Obj::SPELL_SCROLL)
  1207. {
  1208. const std::shared_ptr<Bonus> b = storedArtifact->getBonusLocalFirst(Selector::type()(Bonus::SPELL));
  1209. SpellID spellId(b->subtype);
  1210. handler.serializeId("spell", spellId, SpellID::NONE);
  1211. }
  1212. }
  1213. void CGWitchHut::initObj(CRandomGenerator & rand)
  1214. {
  1215. if (allowedAbilities.empty()) //this can happen for RMG. regular maps load abilities from map file
  1216. {
  1217. // Necromancy can't be learned on random maps
  1218. for(int i = 0; i < VLC->skillh->size(); i++)
  1219. if(VLC->skillh->getByIndex(i)->getId() != SecondarySkill::NECROMANCY)
  1220. allowedAbilities.insert(i);
  1221. }
  1222. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, rand);
  1223. }
  1224. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  1225. {
  1226. InfoWindow iw;
  1227. iw.type = EInfoWindowMode::AUTO;
  1228. iw.player = h->getOwner();
  1229. if(!wasVisited(h->tempOwner))
  1230. cb->setObjProperty(id, CGWitchHut::OBJPROP_VISITED, h->tempOwner.getNum());
  1231. ui32 txt_id;
  1232. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  1233. {
  1234. txt_id =172;
  1235. }
  1236. else if(!h->canLearnSkill()) //already all skills slots used
  1237. {
  1238. txt_id = 173;
  1239. }
  1240. else //give sec skill
  1241. {
  1242. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, ability, 1, 0);
  1243. txt_id = 171;
  1244. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  1245. }
  1246. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  1247. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  1248. cb->showInfoDialog(&iw);
  1249. }
  1250. std::string CGWitchHut::getHoverText(PlayerColor player) const
  1251. {
  1252. std::string hoverName = getObjectName();
  1253. if(wasVisited(player))
  1254. {
  1255. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  1256. boost::algorithm::replace_first(hoverName, "%s", VLC->skillh->getByIndex(ability)->getNameTranslated());
  1257. }
  1258. return hoverName;
  1259. }
  1260. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  1261. {
  1262. std::string hoverName = getHoverText(hero->tempOwner);
  1263. if(wasVisited(hero->tempOwner) && hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  1264. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  1265. return hoverName;
  1266. }
  1267. void CGWitchHut::serializeJsonOptions(JsonSerializeFormat & handler)
  1268. {
  1269. //TODO: unify allowed abilities with others - make them std::vector<bool>
  1270. std::vector<bool> temp;
  1271. size_t skillCount = VLC->skillh->size();
  1272. temp.resize(skillCount, false);
  1273. auto standard = VLC->skillh->getDefaultAllowed(); //todo: for WitchHut default is all except Leadership and Necromancy
  1274. if(handler.saving)
  1275. {
  1276. for(si32 i = 0; i < skillCount; ++i)
  1277. if(vstd::contains(allowedAbilities, i))
  1278. temp[i] = true;
  1279. }
  1280. handler.serializeLIC("allowedSkills", &CSkillHandler::decodeSkill, &CSkillHandler::encodeSkill, standard, temp);
  1281. if(!handler.saving)
  1282. {
  1283. allowedAbilities.clear();
  1284. for(si32 i = 0; i < skillCount; ++i)
  1285. if(temp[i])
  1286. allowedAbilities.insert(i);
  1287. }
  1288. }
  1289. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  1290. {
  1291. InfoWindow iw;
  1292. iw.type = EInfoWindowMode::AUTO;
  1293. iw.player = h->tempOwner;
  1294. switch (ID)
  1295. {
  1296. case Obj::REDWOOD_OBSERVATORY:
  1297. case Obj::PILLAR_OF_FIRE:
  1298. {
  1299. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  1300. FoWChange fw;
  1301. fw.player = h->tempOwner;
  1302. fw.mode = 1;
  1303. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  1304. cb->sendAndApply (&fw);
  1305. break;
  1306. }
  1307. case Obj::COVER_OF_DARKNESS:
  1308. {
  1309. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  1310. for (auto & player : cb->gameState()->players)
  1311. {
  1312. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1313. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  1314. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  1315. }
  1316. break;
  1317. }
  1318. }
  1319. cb->showInfoDialog(&iw);
  1320. }
  1321. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  1322. {
  1323. if(spell == SpellID::NONE)
  1324. {
  1325. logGlobal->error("Not initialized shrine visited!");
  1326. return;
  1327. }
  1328. if(!wasVisited(h->tempOwner))
  1329. cb->setObjProperty(id, CGShrine::OBJPROP_VISITED, h->tempOwner.getNum());
  1330. InfoWindow iw;
  1331. iw.type = EInfoWindowMode::AUTO;
  1332. iw.player = h->getOwner();
  1333. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  1334. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  1335. iw.text << ".";
  1336. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  1337. {
  1338. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  1339. }
  1340. else if(h->spellbookContainsSpell(spell))//hero already knows the spell
  1341. {
  1342. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  1343. }
  1344. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && h->maxSpellLevel() < 3) //it's third level spell and hero doesn't have wisdom
  1345. {
  1346. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  1347. }
  1348. else //give spell
  1349. {
  1350. std::set<SpellID> spells;
  1351. spells.insert(spell);
  1352. cb->changeSpells(h, true, spells);
  1353. iw.components.emplace_back(Component::EComponentType::SPELL, spell, 0, 0);
  1354. }
  1355. cb->showInfoDialog(&iw);
  1356. }
  1357. void CGShrine::initObj(CRandomGenerator & rand)
  1358. {
  1359. if(spell == SpellID::NONE) //spell not set
  1360. {
  1361. int level = ID-87;
  1362. std::vector<SpellID> possibilities;
  1363. cb->getAllowedSpells (possibilities, level);
  1364. if(possibilities.empty())
  1365. {
  1366. logGlobal->error("Error: cannot init shrine, no allowed spells!");
  1367. return;
  1368. }
  1369. spell = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1370. }
  1371. }
  1372. std::string CGShrine::getHoverText(PlayerColor player) const
  1373. {
  1374. std::string hoverName = getObjectName();
  1375. if(wasVisited(player))
  1376. {
  1377. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  1378. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->getNameTranslated());
  1379. }
  1380. return hoverName;
  1381. }
  1382. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  1383. {
  1384. std::string hoverName = getHoverText(hero->tempOwner);
  1385. if(wasVisited(hero->tempOwner) && hero->spellbookContainsSpell(spell)) //know what spell there is and hero knows that spell
  1386. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  1387. return hoverName;
  1388. }
  1389. void CGShrine::serializeJsonOptions(JsonSerializeFormat & handler)
  1390. {
  1391. handler.serializeId("spell", spell, SpellID::NONE);
  1392. }
  1393. void CGSignBottle::initObj(CRandomGenerator & rand)
  1394. {
  1395. //if no text is set than we pick random from the predefined ones
  1396. if(message.empty())
  1397. {
  1398. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  1399. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  1400. message = VLC->generaltexth->translate(messageIdentifier);
  1401. }
  1402. if(ID == Obj::OCEAN_BOTTLE)
  1403. {
  1404. blockVisit = true;
  1405. }
  1406. }
  1407. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  1408. {
  1409. InfoWindow iw;
  1410. iw.player = h->getOwner();
  1411. iw.text << message;
  1412. cb->showInfoDialog(&iw);
  1413. if(ID == Obj::OCEAN_BOTTLE)
  1414. cb->removeObject(this);
  1415. }
  1416. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  1417. {
  1418. handler.serializeString("text", message);
  1419. }
  1420. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  1421. {
  1422. EBonusType type = bonusType;
  1423. int bid = bonusID;
  1424. //check if the bonus if applicable, if not - give primary skill (always possible)
  1425. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  1426. 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)
  1427. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  1428. {
  1429. type = PRIM_SKILL;
  1430. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1431. }
  1432. InfoWindow iw;
  1433. iw.type = EInfoWindowMode::AUTO;
  1434. iw.player = h->getOwner();
  1435. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  1436. switch (type)
  1437. {
  1438. case PRIM_SKILL:
  1439. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  1440. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, bid, +1, 0);
  1441. break;
  1442. case SECONDARY_SKILL:
  1443. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  1444. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, bid, ssl + 1, 0);
  1445. break;
  1446. case SPELL:
  1447. {
  1448. std::set<SpellID> hlp;
  1449. hlp.insert(SpellID(bid));
  1450. cb->changeSpells(h,true,hlp);
  1451. iw.components.emplace_back(Component::EComponentType::SPELL, bid, 0, 0);
  1452. }
  1453. break;
  1454. default:
  1455. logGlobal->error("Error: wrong bonus type (%d) for Scholar!\n", static_cast<int>(type));
  1456. return;
  1457. }
  1458. cb->showInfoDialog(&iw);
  1459. cb->removeObject(this);
  1460. }
  1461. void CGScholar::initObj(CRandomGenerator & rand)
  1462. {
  1463. blockVisit = true;
  1464. if(bonusType == RANDOM)
  1465. {
  1466. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  1467. switch(bonusType)
  1468. {
  1469. case PRIM_SKILL:
  1470. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  1471. break;
  1472. case SECONDARY_SKILL:
  1473. bonusID = rand.nextInt(static_cast<int>(VLC->skillh->size()) - 1);
  1474. break;
  1475. case SPELL:
  1476. std::vector<SpellID> possibilities;
  1477. for (int i = 1; i < 6; ++i)
  1478. cb->getAllowedSpells (possibilities, i);
  1479. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1480. break;
  1481. }
  1482. }
  1483. }
  1484. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  1485. {
  1486. if(handler.saving)
  1487. {
  1488. std::string value;
  1489. switch(bonusType)
  1490. {
  1491. case PRIM_SKILL:
  1492. value = PrimarySkill::names[bonusID];
  1493. handler.serializeString("rewardPrimSkill", value);
  1494. break;
  1495. case SECONDARY_SKILL:
  1496. value = CSkillHandler::encodeSkill(bonusID);
  1497. handler.serializeString("rewardSkill", value);
  1498. break;
  1499. case SPELL:
  1500. value = SpellID::encode(bonusID);
  1501. handler.serializeString("rewardSpell", value);
  1502. break;
  1503. case RANDOM:
  1504. break;
  1505. }
  1506. }
  1507. else
  1508. {
  1509. //TODO: unify
  1510. const JsonNode & json = handler.getCurrent();
  1511. bonusType = RANDOM;
  1512. if(!json["rewardPrimSkill"].String().empty())
  1513. {
  1514. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "primSkill", json["rewardPrimSkill"].String());
  1515. if(raw)
  1516. {
  1517. bonusType = PRIM_SKILL;
  1518. bonusID = raw.get();
  1519. }
  1520. }
  1521. else if(!json["rewardSkill"].String().empty())
  1522. {
  1523. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "skill", json["rewardSkill"].String());
  1524. if(raw)
  1525. {
  1526. bonusType = SECONDARY_SKILL;
  1527. bonusID = raw.get();
  1528. }
  1529. }
  1530. else if(!json["rewardSpell"].String().empty())
  1531. {
  1532. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "spell", json["rewardSpell"].String());
  1533. if(raw)
  1534. {
  1535. bonusType = SPELL;
  1536. bonusID = raw.get();
  1537. }
  1538. }
  1539. }
  1540. }
  1541. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1542. {
  1543. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1544. if (!ally && stacksCount() > 0) {
  1545. //TODO: Find a way to apply magic garrison effects in battle.
  1546. cb->startBattleI(h, this);
  1547. return;
  1548. }
  1549. //New owner.
  1550. if (!ally)
  1551. cb->setOwner(this, h->tempOwner);
  1552. cb->showGarrisonDialog(id, h->id, removableUnits);
  1553. }
  1554. bool CGGarrison::passableFor(PlayerColor player) const
  1555. {
  1556. //FIXME: identical to same method in CGTownInstance
  1557. if ( !stacksCount() )//empty - anyone can visit
  1558. return true;
  1559. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1560. return false;
  1561. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1562. return true;
  1563. return false;
  1564. }
  1565. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1566. {
  1567. if (result.winner == 0)
  1568. onHeroVisit(hero);
  1569. }
  1570. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1571. {
  1572. handler.serializeBool("removableUnits", removableUnits);
  1573. serializeJsonOwner(handler);
  1574. CCreatureSet::serializeJson(handler, "army", 7);
  1575. }
  1576. void CGMagi::reset()
  1577. {
  1578. eyelist.clear();
  1579. }
  1580. void CGMagi::initObj(CRandomGenerator & rand)
  1581. {
  1582. if (ID == Obj::EYE_OF_MAGI)
  1583. {
  1584. blockVisit = true;
  1585. eyelist[subID].push_back(id);
  1586. }
  1587. }
  1588. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1589. {
  1590. if (ID == Obj::HUT_OF_MAGI)
  1591. {
  1592. h->showInfoDialog(61);
  1593. if (!eyelist[subID].empty())
  1594. {
  1595. CenterView cv;
  1596. cv.player = h->tempOwner;
  1597. cv.focusTime = 2000;
  1598. FoWChange fw;
  1599. fw.player = h->tempOwner;
  1600. fw.mode = 1;
  1601. fw.waitForDialogs = true;
  1602. for(const auto & it : eyelist[subID])
  1603. {
  1604. const CGObjectInstance *eye = cb->getObj(it);
  1605. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1606. cb->sendAndApply(&fw);
  1607. cv.pos = eye->pos;
  1608. cb->sendAndApply(&cv);
  1609. }
  1610. cv.pos = h->visitablePos();
  1611. cv.focusTime = 0;
  1612. cb->sendAndApply(&cv);
  1613. }
  1614. }
  1615. else if (ID == Obj::EYE_OF_MAGI)
  1616. {
  1617. h->showInfoDialog(48);
  1618. }
  1619. }
  1620. void CGBoat::initObj(CRandomGenerator & rand)
  1621. {
  1622. hero = nullptr;
  1623. }
  1624. void CGSirens::initObj(CRandomGenerator & rand)
  1625. {
  1626. blockVisit = true;
  1627. }
  1628. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1629. {
  1630. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(Bonus::OBJECT,ID));
  1631. }
  1632. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1633. {
  1634. InfoWindow iw;
  1635. iw.player = h->tempOwner;
  1636. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  1637. {
  1638. iw.type = EInfoWindowMode::AUTO;
  1639. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1640. }
  1641. else
  1642. {
  1643. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  1644. TExpType xp = 0;
  1645. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1646. {
  1647. // 1-sized stacks are not affected by sirens
  1648. if (i->second->count == 1)
  1649. continue;
  1650. // tested H3 behavior: 30% (rounded up) of stack drowns
  1651. TQuantity drown = std::ceil(i->second->count * 0.3);
  1652. if(drown)
  1653. {
  1654. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1655. xp += drown * i->second->type->MaxHealth();
  1656. }
  1657. }
  1658. if(xp)
  1659. {
  1660. xp = h->calculateXp(static_cast<int>(xp));
  1661. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1662. iw.text.addReplacement(static_cast<int>(xp));
  1663. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1664. }
  1665. else
  1666. {
  1667. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1668. }
  1669. }
  1670. cb->showInfoDialog(&iw);
  1671. }
  1672. CGShipyard::CGShipyard()
  1673. :IShipyard(this)
  1674. {
  1675. }
  1676. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1677. {
  1678. // H J L K I
  1679. // A x S x B
  1680. // C E G F D
  1681. offsets = {
  1682. int3(-3,0,0), int3(1,0,0), //AB
  1683. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1684. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1685. };
  1686. }
  1687. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1688. {
  1689. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1690. cb->setOwner(this, h->tempOwner);
  1691. auto s = shipyardStatus();
  1692. if(s != IBoatGenerator::GOOD)
  1693. {
  1694. InfoWindow iw;
  1695. iw.type = EInfoWindowMode::AUTO;
  1696. iw.player = tempOwner;
  1697. getProblemText(iw.text, h);
  1698. cb->showInfoDialog(&iw);
  1699. }
  1700. else
  1701. {
  1702. openWindow(EOpenWindowMode::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1703. }
  1704. }
  1705. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1706. {
  1707. serializeJsonOwner(handler);
  1708. }
  1709. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1710. {
  1711. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1712. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1713. {
  1714. if (cb->getResource(h->tempOwner, EGameResID::GOLD) >= 1000) //if he can afford a map
  1715. {
  1716. //ask if he wants to buy one
  1717. int text=0;
  1718. switch (subID)
  1719. {
  1720. case 0:
  1721. text = 25;
  1722. break;
  1723. case 1:
  1724. text = 26;
  1725. break;
  1726. case 2:
  1727. text = 27;
  1728. break;
  1729. default:
  1730. logGlobal->warn("Unrecognized subtype of cartographer");
  1731. }
  1732. assert(text);
  1733. BlockingDialog bd (true, false);
  1734. bd.player = h->getOwner();
  1735. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1736. cb->showBlockingDialog (&bd);
  1737. }
  1738. else //if he cannot afford
  1739. {
  1740. h->showInfoDialog(28);
  1741. }
  1742. }
  1743. else //if he already visited carographer
  1744. {
  1745. h->showInfoDialog(24);
  1746. }
  1747. }
  1748. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1749. {
  1750. if(answer) //if hero wants to buy map
  1751. {
  1752. cb->giveResource(hero->tempOwner, EGameResID::GOLD, -1000);
  1753. FoWChange fw;
  1754. fw.mode = 1;
  1755. fw.player = hero->tempOwner;
  1756. //subIDs of different types of cartographers:
  1757. //water = 0; land = 1; underground = 2;
  1758. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1759. switch(subID)
  1760. {
  1761. case 0:
  1762. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1763. break;
  1764. case 1:
  1765. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1766. break;
  1767. case 2:
  1768. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1769. break;
  1770. }
  1771. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1772. cb->sendAndApply(&fw);
  1773. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1774. }
  1775. }
  1776. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1777. {
  1778. cb->showThievesGuildWindow(h->tempOwner, id);
  1779. }
  1780. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1781. {
  1782. InfoWindow iw;
  1783. iw.type = EInfoWindowMode::AUTO;
  1784. iw.player = h->tempOwner;
  1785. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1786. assert(ts);
  1787. TeamID team = ts->id;
  1788. if(!wasVisited(team))
  1789. {
  1790. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1791. cb->sendAndApply(&iw);
  1792. // increment general visited obelisks counter
  1793. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1794. openWindow(EOpenWindowMode::PUZZLE_MAP, h->tempOwner.getNum());
  1795. // mark that particular obelisk as visited for all players in the team
  1796. for(const auto & color : ts->players)
  1797. {
  1798. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1799. }
  1800. }
  1801. else
  1802. {
  1803. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1804. cb->sendAndApply(&iw);
  1805. }
  1806. }
  1807. void CGObelisk::initObj(CRandomGenerator & rand)
  1808. {
  1809. obeliskCount++;
  1810. }
  1811. void CGObelisk::reset()
  1812. {
  1813. obeliskCount = 0;
  1814. visited.clear();
  1815. }
  1816. std::string CGObelisk::getHoverText(PlayerColor player) const
  1817. {
  1818. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1819. }
  1820. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1821. {
  1822. switch(what)
  1823. {
  1824. case CGObelisk::OBJPROP_INC:
  1825. {
  1826. auto progress = ++visited[TeamID(val)];
  1827. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1828. if(progress > obeliskCount)
  1829. {
  1830. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1831. throw std::runtime_error("internal error");
  1832. }
  1833. break;
  1834. }
  1835. default:
  1836. CTeamVisited::setPropertyDer(what, val);
  1837. break;
  1838. }
  1839. }
  1840. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1841. {
  1842. if(h->tempOwner != tempOwner)
  1843. {
  1844. PlayerColor oldOwner = tempOwner;
  1845. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1846. h->showInfoDialog(69);
  1847. giveBonusTo(h->tempOwner);
  1848. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1849. {
  1850. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1851. rb.whoID = oldOwner.getNum();
  1852. rb.source = Bonus::OBJECT;
  1853. rb.id = id.getNum();
  1854. cb->sendAndApply(&rb);
  1855. }
  1856. }
  1857. }
  1858. void CGLighthouse::initObj(CRandomGenerator & rand)
  1859. {
  1860. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1861. {
  1862. // FIXME: This is dirty hack
  1863. giveBonusTo(tempOwner, true);
  1864. }
  1865. }
  1866. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1867. {
  1868. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1869. gb.bonus.type = Bonus::MOVEMENT;
  1870. gb.bonus.val = 500;
  1871. gb.id = player.getNum();
  1872. gb.bonus.duration = Bonus::PERMANENT;
  1873. gb.bonus.source = Bonus::OBJECT;
  1874. gb.bonus.sid = id.getNum();
  1875. gb.bonus.subtype = 1;
  1876. // FIXME: This is really dirty hack
  1877. // Proper fix would be to make CGLighthouse into bonus system node
  1878. // Unfortunately this will cause saves breakage
  1879. if(onInit)
  1880. gb.applyGs(cb->gameState());
  1881. else
  1882. cb->sendAndApply(&gb);
  1883. }
  1884. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1885. {
  1886. serializeJsonOwner(handler);
  1887. }
  1888. VCMI_LIB_NAMESPACE_END