MiscObjects.cpp 55 KB

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