MiscObjects.cpp 55 KB

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