MiscObjects.cpp 56 KB

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