MiscObjects.cpp 47 KB

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