MiscObjects.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. bool CGGarrison::passableFor(PlayerColor player) const
  1115. {
  1116. //FIXME: identical to same method in CGTownInstance
  1117. if ( !stacksCount() )//empty - anyone can visit
  1118. return true;
  1119. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1120. return false;
  1121. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1122. return true;
  1123. return false;
  1124. }
  1125. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1126. {
  1127. if (result.winner == 0)
  1128. onHeroVisit(hero);
  1129. }
  1130. void CGMagi::initObj()
  1131. {
  1132. if (ID == Obj::EYE_OF_MAGI)
  1133. {
  1134. blockVisit = true;
  1135. eyelist[subID].push_back(id);
  1136. }
  1137. }
  1138. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1139. {
  1140. if (ID == Obj::HUT_OF_MAGI)
  1141. {
  1142. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  1143. if (!eyelist[subID].empty())
  1144. {
  1145. CenterView cv;
  1146. cv.player = h->tempOwner;
  1147. cv.focusTime = 2000;
  1148. FoWChange fw;
  1149. fw.player = h->tempOwner;
  1150. fw.mode = 1;
  1151. for(auto it : eyelist[subID])
  1152. {
  1153. const CGObjectInstance *eye = cb->getObj(it);
  1154. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1155. cb->sendAndApply(&fw);
  1156. cv.pos = eye->pos;
  1157. cb->sendAndApply(&cv);
  1158. }
  1159. cv.pos = h->getPosition(false);
  1160. cb->sendAndApply(&cv);
  1161. }
  1162. }
  1163. else if (ID == Obj::EYE_OF_MAGI)
  1164. {
  1165. showInfoDialog(h,48,soundBase::invalid);
  1166. }
  1167. }
  1168. void CGBoat::initObj()
  1169. {
  1170. hero = nullptr;
  1171. }
  1172. void CGSirens::initObj()
  1173. {
  1174. blockVisit = true;
  1175. }
  1176. const std::string & CGSirens::getHoverText() const
  1177. {
  1178. getNameVis(hoverName);
  1179. return hoverName;
  1180. }
  1181. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1182. {
  1183. InfoWindow iw;
  1184. iw.soundID = soundBase::DANGER;
  1185. iw.player = h->tempOwner;
  1186. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  1187. {
  1188. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1189. }
  1190. else
  1191. {
  1192. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  1193. TExpType xp = 0;
  1194. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1195. {
  1196. TQuantity drown = i->second->count * 0.3;
  1197. if(drown)
  1198. {
  1199. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1200. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  1201. }
  1202. }
  1203. if(xp)
  1204. {
  1205. xp = h->calculateXp(xp);
  1206. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1207. iw.text.addReplacement(xp);
  1208. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1209. }
  1210. else
  1211. {
  1212. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1213. }
  1214. }
  1215. cb->showInfoDialog(&iw);
  1216. }
  1217. CGShipyard::CGShipyard()
  1218. :IShipyard(this)
  1219. {
  1220. }
  1221. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1222. {
  1223. // H J L K I
  1224. // A x S x B
  1225. // C E G F D
  1226. offsets += int3(-3,0,0), int3(1,0,0), //AB
  1227. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1228. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  1229. }
  1230. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1231. {
  1232. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1233. cb->setOwner(this, h->tempOwner);
  1234. auto s = shipyardStatus();
  1235. if(s != IBoatGenerator::GOOD)
  1236. {
  1237. InfoWindow iw;
  1238. iw.player = tempOwner;
  1239. getProblemText(iw.text, h);
  1240. cb->showInfoDialog(&iw);
  1241. }
  1242. else
  1243. {
  1244. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1245. }
  1246. }
  1247. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1248. {
  1249. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  1250. {
  1251. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  1252. {
  1253. //ask if he wants to buy one
  1254. int text=0;
  1255. switch (subID)
  1256. {
  1257. case 0:
  1258. text = 25;
  1259. break;
  1260. case 1:
  1261. text = 26;
  1262. break;
  1263. case 2:
  1264. text = 27;
  1265. break;
  1266. default:
  1267. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  1268. }
  1269. assert(text);
  1270. BlockingDialog bd (true, false);
  1271. bd.player = h->getOwner();
  1272. bd.soundID = soundBase::LIGHTHOUSE;
  1273. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1274. cb->showBlockingDialog (&bd);
  1275. }
  1276. else //if he cannot afford
  1277. {
  1278. showInfoDialog(h,28,soundBase::CAVEHEAD);
  1279. }
  1280. }
  1281. else //if he already visited carographer
  1282. {
  1283. showInfoDialog(h,24,soundBase::CAVEHEAD);
  1284. }
  1285. }
  1286. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1287. {
  1288. if (answer) //if hero wants to buy map
  1289. {
  1290. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  1291. FoWChange fw;
  1292. fw.mode = 1;
  1293. fw.player = hero->tempOwner;
  1294. //subIDs of different types of cartographers:
  1295. //water = 0; land = 1; underground = 2;
  1296. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  1297. cb->sendAndApply (&fw);
  1298. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  1299. }
  1300. }
  1301. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1302. {
  1303. cb->showThievesGuildWindow(h->tempOwner, id);
  1304. }
  1305. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1306. {
  1307. InfoWindow iw;
  1308. iw.player = h->tempOwner;
  1309. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1310. assert(ts);
  1311. TeamID team = ts->id;
  1312. if(!wasVisited(team))
  1313. {
  1314. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1315. cb->sendAndApply(&iw);
  1316. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  1317. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  1318. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  1319. }
  1320. else
  1321. {
  1322. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1323. cb->sendAndApply(&iw);
  1324. }
  1325. }
  1326. void CGObelisk::initObj()
  1327. {
  1328. obeliskCount++;
  1329. }
  1330. const std::string & CGObelisk::getHoverText() const
  1331. {
  1332. bool visited = wasVisited(cb->getLocalPlayer());
  1333. hoverName = VLC->objtypeh->getObjectName(ID) + " " + visitedTxt(visited);
  1334. return hoverName;
  1335. }
  1336. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1337. {
  1338. CPlayersVisited::setPropertyDer(what, val);
  1339. switch(what)
  1340. {
  1341. case 20:
  1342. assert(val < PlayerColor::PLAYER_LIMIT_I);
  1343. visited[TeamID(val)]++;
  1344. if(visited[TeamID(val)] > obeliskCount)
  1345. {
  1346. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  1347. assert(0);
  1348. }
  1349. break;
  1350. }
  1351. }
  1352. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1353. {
  1354. if(h->tempOwner != tempOwner)
  1355. {
  1356. PlayerColor oldOwner = tempOwner;
  1357. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1358. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  1359. giveBonusTo(h->tempOwner);
  1360. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1361. {
  1362. RemoveBonus rb(RemoveBonus::PLAYER);
  1363. rb.whoID = oldOwner.getNum();
  1364. rb.source = Bonus::OBJECT;
  1365. rb.id = id.getNum();
  1366. cb->sendAndApply(&rb);
  1367. }
  1368. }
  1369. }
  1370. void CGLighthouse::initObj()
  1371. {
  1372. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1373. {
  1374. giveBonusTo(tempOwner);
  1375. }
  1376. }
  1377. const std::string & CGLighthouse::getHoverText() const
  1378. {
  1379. hoverName = VLC->objtypeh->getObjectName(ID);
  1380. //TODO: owned by %s player
  1381. return hoverName;
  1382. }
  1383. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  1384. {
  1385. GiveBonus gb(GiveBonus::PLAYER);
  1386. gb.bonus.type = Bonus::SEA_MOVEMENT;
  1387. gb.bonus.val = 500;
  1388. gb.id = player.getNum();
  1389. gb.bonus.duration = Bonus::PERMANENT;
  1390. gb.bonus.source = Bonus::OBJECT;
  1391. gb.bonus.sid = id.getNum();
  1392. cb->sendAndApply(&gb);
  1393. }