MiscObjects.cpp 42 KB

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