MiscObjects.cpp 54 KB

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