MiscObjects.cpp 55 KB

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