MiscObjects.cpp 55 KB

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