MiscObjects.cpp 40 KB

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