MiscObjects.cpp 55 KB

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