MiscObjects.cpp 40 KB

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