MiscObjects.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  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(CRandomGenerator & rand)
  182. {
  183. blockVisit = true;
  184. switch(character)
  185. {
  186. case 0:
  187. character = -4;
  188. break;
  189. case 1:
  190. character = rand.nextInt(1, 7);
  191. break;
  192. case 2:
  193. character = rand.nextInt(1, 10);
  194. break;
  195. case 3:
  196. character = rand.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 = rand.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 * (ui64)1000;
  215. refusedJoining = false;
  216. }
  217. void CGCreature::newTurn(CRandomGenerator & rand) 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, CRandomGenerator::getDefault());
  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(CRandomGenerator & rand) 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(CRandomGenerator & rand)
  600. {
  601. if(isAbandoned())
  602. {
  603. //set guardians
  604. int howManyTroglodytes = rand.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, rand);
  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(CRandomGenerator & rand)
  748. {
  749. blockVisit = true;
  750. if(!amount)
  751. {
  752. switch(subID)
  753. {
  754. case Res::GOLD:
  755. amount = rand.nextInt(5, 10) * 100;
  756. break;
  757. case Res::WOOD: case Res::ORE:
  758. amount = rand.nextInt(6, 10);
  759. break;
  760. default:
  761. amount = rand.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, CRandomGenerator::getDefault());
  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(CRandomGenerator & rand)
  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(CRandomGenerator & rand)
  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, CRandomGenerator::getDefault()), 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(CRandomGenerator & rand)
  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 std::shared_ptr<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(CRandomGenerator & rand)
  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, rand);
  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(vstd::contains(h->spells,spell))//hero already knows the spell
  1411. {
  1412. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  1413. }
  1414. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  1415. {
  1416. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  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(CRandomGenerator & rand)
  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, rand);
  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(wasVisited(hero->tempOwner) && vstd::contains(hero->spells, spell)) //know what spell there is and 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(CRandomGenerator & rand)
  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, rand);
  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 && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  1496. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  1497. {
  1498. type = PRIM_SKILL;
  1499. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1500. }
  1501. InfoWindow iw;
  1502. iw.soundID = soundBase::gazebo;
  1503. iw.player = h->getOwner();
  1504. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  1505. switch (type)
  1506. {
  1507. case PRIM_SKILL:
  1508. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  1509. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  1510. break;
  1511. case SECONDARY_SKILL:
  1512. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  1513. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  1514. break;
  1515. case SPELL:
  1516. {
  1517. std::set<SpellID> hlp;
  1518. hlp.insert(SpellID(bid));
  1519. cb->changeSpells(h,true,hlp);
  1520. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  1521. }
  1522. break;
  1523. default:
  1524. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  1525. return;
  1526. }
  1527. cb->showInfoDialog(&iw);
  1528. cb->removeObject(this);
  1529. }
  1530. void CGScholar::initObj(CRandomGenerator & rand)
  1531. {
  1532. blockVisit = true;
  1533. if(bonusType == RANDOM)
  1534. {
  1535. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  1536. switch(bonusType)
  1537. {
  1538. case PRIM_SKILL:
  1539. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  1540. break;
  1541. case SECONDARY_SKILL:
  1542. bonusID = rand.nextInt(GameConstants::SKILL_QUANTITY -1);
  1543. break;
  1544. case SPELL:
  1545. std::vector<SpellID> possibilities;
  1546. for (int i = 1; i < 6; ++i)
  1547. cb->getAllowedSpells (possibilities, i);
  1548. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1549. break;
  1550. }
  1551. }
  1552. }
  1553. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  1554. {
  1555. JsonNode& json = handler.getCurrent();
  1556. if(handler.saving)
  1557. {
  1558. switch(bonusType)
  1559. {
  1560. case PRIM_SKILL:
  1561. json["rewardPrimSkill"].String() = PrimarySkill::names[bonusID];
  1562. break;
  1563. case SECONDARY_SKILL:
  1564. json["rewardSkill"].String() = NSecondarySkill::names[bonusID];
  1565. break;
  1566. case SPELL:
  1567. json["rewardSpell"].String() = VLC->spellh->objects.at(bonusID)->identifier;
  1568. break;
  1569. case RANDOM:
  1570. break;
  1571. }
  1572. }
  1573. else
  1574. {
  1575. bonusType = RANDOM;
  1576. if(json["rewardPrimSkill"].String() != "")
  1577. {
  1578. auto raw = VLC->modh->identifiers.getIdentifier("core", "primSkill", json["rewardPrimSkill"].String());
  1579. if(raw)
  1580. {
  1581. bonusType = PRIM_SKILL;
  1582. bonusID = raw.get();
  1583. }
  1584. }
  1585. else if(json["rewardSkill"].String() != "")
  1586. {
  1587. auto raw = VLC->modh->identifiers.getIdentifier("core", "skill", json["rewardSkill"].String());
  1588. if(raw)
  1589. {
  1590. bonusType = SECONDARY_SKILL;
  1591. bonusID = raw.get();
  1592. }
  1593. }
  1594. else if(json["rewardSpell"].String() != "")
  1595. {
  1596. auto raw = VLC->modh->identifiers.getIdentifier("core", "spell", json["rewardSpell"].String());
  1597. if(raw)
  1598. {
  1599. bonusType = SPELL;
  1600. bonusID = raw.get();
  1601. }
  1602. }
  1603. }
  1604. }
  1605. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1606. {
  1607. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1608. if (!ally && stacksCount() > 0) {
  1609. //TODO: Find a way to apply magic garrison effects in battle.
  1610. cb->startBattleI(h, this);
  1611. return;
  1612. }
  1613. //New owner.
  1614. if (!ally)
  1615. cb->setOwner(this, h->tempOwner);
  1616. cb->showGarrisonDialog(id, h->id, removableUnits);
  1617. }
  1618. bool CGGarrison::passableFor(PlayerColor player) const
  1619. {
  1620. //FIXME: identical to same method in CGTownInstance
  1621. if ( !stacksCount() )//empty - anyone can visit
  1622. return true;
  1623. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1624. return false;
  1625. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1626. return true;
  1627. return false;
  1628. }
  1629. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1630. {
  1631. if (result.winner == 0)
  1632. onHeroVisit(hero);
  1633. }
  1634. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1635. {
  1636. handler.serializeBool("removableUnits", removableUnits);
  1637. serializeJsonOwner(handler);
  1638. CCreatureSet::serializeJson(handler, "army");
  1639. }
  1640. void CGMagi::reset()
  1641. {
  1642. eyelist.clear();
  1643. }
  1644. void CGMagi::initObj(CRandomGenerator & rand)
  1645. {
  1646. if (ID == Obj::EYE_OF_MAGI)
  1647. {
  1648. blockVisit = true;
  1649. eyelist[subID].push_back(id);
  1650. }
  1651. }
  1652. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1653. {
  1654. if (ID == Obj::HUT_OF_MAGI)
  1655. {
  1656. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  1657. if (!eyelist[subID].empty())
  1658. {
  1659. CenterView cv;
  1660. cv.player = h->tempOwner;
  1661. cv.focusTime = 2000;
  1662. FoWChange fw;
  1663. fw.player = h->tempOwner;
  1664. fw.mode = 1;
  1665. fw.waitForDialogs = true;
  1666. for(auto it : eyelist[subID])
  1667. {
  1668. const CGObjectInstance *eye = cb->getObj(it);
  1669. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1670. cb->sendAndApply(&fw);
  1671. cv.pos = eye->pos;
  1672. cb->sendAndApply(&cv);
  1673. }
  1674. cv.pos = h->getPosition(false);
  1675. cv.focusTime = 0;
  1676. cb->sendAndApply(&cv);
  1677. }
  1678. }
  1679. else if (ID == Obj::EYE_OF_MAGI)
  1680. {
  1681. showInfoDialog(h,48,soundBase::invalid);
  1682. }
  1683. }
  1684. void CGBoat::initObj(CRandomGenerator & rand)
  1685. {
  1686. hero = nullptr;
  1687. }
  1688. void CGSirens::initObj(CRandomGenerator & rand)
  1689. {
  1690. blockVisit = true;
  1691. }
  1692. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1693. {
  1694. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(Bonus::OBJECT,ID));
  1695. }
  1696. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1697. {
  1698. InfoWindow iw;
  1699. iw.soundID = soundBase::DANGER;
  1700. iw.player = h->tempOwner;
  1701. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  1702. {
  1703. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1704. }
  1705. else
  1706. {
  1707. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  1708. TExpType xp = 0;
  1709. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1710. {
  1711. TQuantity drown = i->second->count * 0.3;
  1712. if(drown)
  1713. {
  1714. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1715. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  1716. }
  1717. }
  1718. if(xp)
  1719. {
  1720. xp = h->calculateXp(xp);
  1721. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1722. iw.text.addReplacement(xp);
  1723. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1724. }
  1725. else
  1726. {
  1727. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1728. }
  1729. }
  1730. cb->showInfoDialog(&iw);
  1731. }
  1732. CGShipyard::CGShipyard()
  1733. :IShipyard(this)
  1734. {
  1735. }
  1736. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1737. {
  1738. // H J L K I
  1739. // A x S x B
  1740. // C E G F D
  1741. offsets = {
  1742. int3(-3,0,0), int3(1,0,0), //AB
  1743. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1744. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1745. };
  1746. }
  1747. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1748. {
  1749. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1750. cb->setOwner(this, h->tempOwner);
  1751. auto s = shipyardStatus();
  1752. if(s != IBoatGenerator::GOOD)
  1753. {
  1754. InfoWindow iw;
  1755. iw.player = tempOwner;
  1756. getProblemText(iw.text, h);
  1757. cb->showInfoDialog(&iw);
  1758. }
  1759. else
  1760. {
  1761. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1762. }
  1763. }
  1764. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1765. {
  1766. serializeJsonOwner(handler);
  1767. }
  1768. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1769. {
  1770. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1771. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1772. {
  1773. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  1774. {
  1775. //ask if he wants to buy one
  1776. int text=0;
  1777. switch (subID)
  1778. {
  1779. case 0:
  1780. text = 25;
  1781. break;
  1782. case 1:
  1783. text = 26;
  1784. break;
  1785. case 2:
  1786. text = 27;
  1787. break;
  1788. default:
  1789. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  1790. }
  1791. assert(text);
  1792. BlockingDialog bd (true, false);
  1793. bd.player = h->getOwner();
  1794. bd.soundID = soundBase::LIGHTHOUSE;
  1795. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1796. cb->showBlockingDialog (&bd);
  1797. }
  1798. else //if he cannot afford
  1799. {
  1800. showInfoDialog(h,28,soundBase::CAVEHEAD);
  1801. }
  1802. }
  1803. else //if he already visited carographer
  1804. {
  1805. showInfoDialog(h,24,soundBase::CAVEHEAD);
  1806. }
  1807. }
  1808. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1809. {
  1810. if (answer) //if hero wants to buy map
  1811. {
  1812. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  1813. FoWChange fw;
  1814. fw.mode = 1;
  1815. fw.player = hero->tempOwner;
  1816. //subIDs of different types of cartographers:
  1817. //water = 0; land = 1; underground = 2;
  1818. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  1819. cb->sendAndApply (&fw);
  1820. cb->setObjProperty (id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1821. }
  1822. }
  1823. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1824. {
  1825. cb->showThievesGuildWindow(h->tempOwner, id);
  1826. }
  1827. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1828. {
  1829. InfoWindow iw;
  1830. iw.player = h->tempOwner;
  1831. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1832. assert(ts);
  1833. TeamID team = ts->id;
  1834. if(!wasVisited(team))
  1835. {
  1836. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1837. cb->sendAndApply(&iw);
  1838. // increment general visited obelisks counter
  1839. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1840. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  1841. // mark that particular obelisk as visited for all players in the team
  1842. for (auto & color : ts->players)
  1843. {
  1844. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1845. }
  1846. }
  1847. else
  1848. {
  1849. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1850. cb->sendAndApply(&iw);
  1851. }
  1852. }
  1853. void CGObelisk::initObj(CRandomGenerator & rand)
  1854. {
  1855. obeliskCount++;
  1856. }
  1857. void CGObelisk::reset()
  1858. {
  1859. obeliskCount = 0;
  1860. visited.clear();
  1861. }
  1862. std::string CGObelisk::getHoverText(PlayerColor player) const
  1863. {
  1864. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1865. }
  1866. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1867. {
  1868. switch(what)
  1869. {
  1870. case CGObelisk::OBJPROP_INC:
  1871. {
  1872. assert(val < PlayerColor::PLAYER_LIMIT_I);
  1873. auto progress = ++visited[TeamID(val)];
  1874. logGlobal->debugStream() << boost::format("Player %d: obelisk progress %d / %d")
  1875. % val % static_cast<int>(progress) % static_cast<int>(obeliskCount);
  1876. if(progress > obeliskCount)
  1877. {
  1878. logGlobal->errorStream() << "Error: Visited " << progress << "\t\t" << obeliskCount;
  1879. assert(0);
  1880. }
  1881. break;
  1882. }
  1883. default:
  1884. CPlayersVisited::setPropertyDer(what, val);
  1885. break;
  1886. }
  1887. }
  1888. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1889. {
  1890. if(h->tempOwner != tempOwner)
  1891. {
  1892. PlayerColor oldOwner = tempOwner;
  1893. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1894. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  1895. giveBonusTo(h->tempOwner);
  1896. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1897. {
  1898. RemoveBonus rb(RemoveBonus::PLAYER);
  1899. rb.whoID = oldOwner.getNum();
  1900. rb.source = Bonus::OBJECT;
  1901. rb.id = id.getNum();
  1902. cb->sendAndApply(&rb);
  1903. }
  1904. }
  1905. }
  1906. void CGLighthouse::initObj(CRandomGenerator & rand)
  1907. {
  1908. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1909. {
  1910. giveBonusTo(tempOwner);
  1911. }
  1912. }
  1913. std::string CGLighthouse::getHoverText(PlayerColor player) const
  1914. {
  1915. //TODO: owned by %s player
  1916. return getObjectName();
  1917. }
  1918. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  1919. {
  1920. GiveBonus gb(GiveBonus::PLAYER);
  1921. gb.bonus.type = Bonus::SEA_MOVEMENT;
  1922. gb.bonus.val = 500;
  1923. gb.id = player.getNum();
  1924. gb.bonus.duration = Bonus::PERMANENT;
  1925. gb.bonus.source = Bonus::OBJECT;
  1926. gb.bonus.sid = id.getNum();
  1927. cb->sendAndApply(&gb);
  1928. }
  1929. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1930. {
  1931. serializeJsonOwner(handler);
  1932. }