2
0

MiscObjects.cpp 55 KB

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