MiscObjects.cpp 56 KB

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