MiscObjects.cpp 55 KB

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