MiscObjects.cpp 55 KB

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