CGTownInstance.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. /*
  2. * CGTownInstance.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 "CGTownInstance.h"
  12. #include "CObjectClassesHandler.h"
  13. #include "../NetPacks.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../CModHandler.h"
  16. #include "../IGameCallback.h"
  17. #include "../CGameState.h"
  18. #include "../mapping/CMapDefines.h"
  19. #include "../CPlayerState.h"
  20. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  21. std::vector<int> CGTownInstance::universitySkills;
  22. void CGDwelling::initObj()
  23. {
  24. switch(ID)
  25. {
  26. case Obj::CREATURE_GENERATOR1:
  27. case Obj::CREATURE_GENERATOR4:
  28. {
  29. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, cb->gameState()->getRandomGenerator());
  30. if (getOwner() != PlayerColor::NEUTRAL)
  31. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  32. assert(!creatures.empty());
  33. assert(!creatures[0].second.empty());
  34. break;
  35. }
  36. case Obj::REFUGEE_CAMP:
  37. //is handled within newturn func
  38. break;
  39. case Obj::WAR_MACHINE_FACTORY:
  40. creatures.resize(3);
  41. creatures[0].second.push_back(CreatureID::BALLISTA);
  42. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  43. creatures[2].second.push_back(CreatureID::AMMO_CART);
  44. break;
  45. default:
  46. assert(0);
  47. break;
  48. }
  49. }
  50. void CGDwelling::setPropertyDer(ui8 what, ui32 val)
  51. {
  52. switch (what)
  53. {
  54. case ObjProperty::OWNER: //change owner
  55. if (ID == Obj::CREATURE_GENERATOR1) //single generators
  56. {
  57. if (tempOwner != PlayerColor::NEUTRAL)
  58. {
  59. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  60. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  61. }
  62. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  63. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  64. }
  65. break;
  66. case ObjProperty::AVAILABLE_CREATURE:
  67. creatures.resize(1);
  68. creatures[0].second.resize(1);
  69. creatures[0].second[0] = CreatureID(val);
  70. break;
  71. }
  72. }
  73. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  74. {
  75. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  76. {
  77. InfoWindow iw;
  78. iw.player = h->tempOwner;
  79. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  80. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  81. cb->sendAndApply(&iw);
  82. return;
  83. }
  84. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  85. if ( relations == PlayerRelations::ALLIES )
  86. return;//do not allow recruiting or capturing
  87. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  88. {
  89. BlockingDialog bd(true,false);
  90. bd.player = h->tempOwner;
  91. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  92. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  93. bd.text.addReplacement(MetaString::ARRAY_TXT, 176 + Slots().begin()->second->getQuantityID()*3);
  94. bd.text.addReplacement(*Slots().begin()->second);
  95. cb->showBlockingDialog(&bd);
  96. return;
  97. }
  98. // TODO this shouldn't be hardcoded
  99. if(!relations && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  100. {
  101. cb->setOwner(this, h->tempOwner);
  102. }
  103. BlockingDialog bd (true,false);
  104. bd.player = h->tempOwner;
  105. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  106. {
  107. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  108. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  109. for(auto & elem : creatures)
  110. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  111. }
  112. else if(ID == Obj::REFUGEE_CAMP)
  113. {
  114. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  115. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  116. for(auto & elem : creatures)
  117. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  118. }
  119. else if(ID == Obj::WAR_MACHINE_FACTORY)
  120. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  121. else
  122. throw std::runtime_error("Illegal dwelling!");
  123. cb->showBlockingDialog(&bd);
  124. }
  125. void CGDwelling::newTurn() const
  126. {
  127. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  128. return;
  129. //town growths and War Machines Factories are handled separately
  130. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  131. return;
  132. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  133. {
  134. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(cb->gameState()->getRandomGenerator()));
  135. }
  136. bool change = false;
  137. SetAvailableCreatures sac;
  138. sac.creatures = creatures;
  139. sac.tid = id;
  140. for (size_t i = 0; i < creatures.size(); i++)
  141. {
  142. if(creatures[i].second.size())
  143. {
  144. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  145. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  146. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  147. sac.creatures[i].first += amount;
  148. else
  149. sac.creatures[i].first = amount;
  150. change = true;
  151. }
  152. }
  153. if(change)
  154. cb->sendAndApply(&sac);
  155. updateGuards();
  156. }
  157. void CGDwelling::updateGuards() const
  158. {
  159. //TODO: store custom guard config and use it
  160. //TODO: store boolean flag for guards
  161. bool guarded = false;
  162. //default condition - creatures are of level 5 or higher
  163. for (auto creatureEntry : creatures)
  164. {
  165. if (VLC->creh->creatures[creatureEntry.second.at(0)]->level >= 5 && ID != Obj::REFUGEE_CAMP)
  166. {
  167. guarded = true;
  168. break;
  169. }
  170. }
  171. if (guarded)
  172. {
  173. for (auto creatureEntry : creatures)
  174. {
  175. const CCreature * crea = VLC->creh->creatures[creatureEntry.second.at(0)];
  176. SlotID slot = getSlotFor(crea->idNumber);
  177. StackLocation stackLocation = StackLocation(this, slot);;
  178. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  179. {
  180. ChangeStackCount csc;
  181. csc.sl = stackLocation;
  182. csc.count = crea->growth * 3;
  183. csc.absoluteValue = true;
  184. cb->sendAndApply(&csc);
  185. }
  186. else //slot is empty, create whole new stack
  187. {
  188. InsertNewStack ns;
  189. ns.sl = stackLocation;
  190. ns.stack = CStackBasicDescriptor(crea->idNumber, crea->growth * 3);
  191. cb->sendAndApply(&ns);
  192. }
  193. }
  194. }
  195. }
  196. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  197. {
  198. CreatureID crid = creatures[0].second[0];
  199. CCreature *crs = VLC->creh->creatures[crid];
  200. TQuantity count = creatures[0].first;
  201. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  202. {
  203. if(count) //there are available creatures
  204. {
  205. SlotID slot = h->getSlotFor(crid);
  206. if(!slot.validSlot()) //no available slot
  207. {
  208. InfoWindow iw;
  209. iw.player = h->tempOwner;
  210. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  211. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  212. cb->showInfoDialog(&iw);
  213. }
  214. else //give creatures
  215. {
  216. SetAvailableCreatures sac;
  217. sac.tid = id;
  218. sac.creatures = creatures;
  219. sac.creatures[0].first = 0;
  220. InfoWindow iw;
  221. iw.player = h->tempOwner;
  222. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  223. iw.text.addReplacement(count);
  224. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  225. cb->showInfoDialog(&iw);
  226. cb->sendAndApply(&sac);
  227. cb->addToSlot(StackLocation(h, slot), crs, count);
  228. }
  229. }
  230. else //there no creatures
  231. {
  232. InfoWindow iw;
  233. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  234. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  235. iw.player = h->tempOwner;
  236. cb->sendAndApply(&iw);
  237. }
  238. }
  239. else
  240. {
  241. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  242. {
  243. //there is 1 war machine available to recruit if hero doesn't have one
  244. SetAvailableCreatures sac;
  245. sac.tid = id;
  246. sac.creatures = creatures;
  247. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  248. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  249. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  250. cb->sendAndApply(&sac);
  251. }
  252. OpenWindow ow;
  253. ow.id1 = id.getNum();
  254. ow.id2 = h->id.getNum();
  255. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  256. ? OpenWindow::RECRUITMENT_FIRST
  257. : OpenWindow::RECRUITMENT_ALL;
  258. cb->sendAndApply(&ow);
  259. }
  260. }
  261. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  262. {
  263. if (result.winner == 0)
  264. {
  265. onHeroVisit(hero);
  266. }
  267. }
  268. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  269. {
  270. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  271. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  272. {
  273. if(answer)
  274. cb->startBattleI(hero, this);
  275. }
  276. else if(answer)
  277. {
  278. heroAcceptsCreatures(hero);
  279. }
  280. }
  281. int CGTownInstance::getSightRadius() const //returns sight distance
  282. {
  283. if (subID == ETownType::TOWER)
  284. {
  285. if (hasBuilt(BuildingID::GRAIL)) //skyship
  286. return -1; //entire map
  287. if (hasBuilt(BuildingID::LOOKOUT_TOWER)) //lookout tower
  288. return 20;
  289. }
  290. return 5;
  291. }
  292. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  293. {
  294. ///this is freakin' overcomplicated solution
  295. switch (what)
  296. {
  297. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  298. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  299. break;
  300. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  301. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  302. break;
  303. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  304. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  305. break;
  306. case ObjProperty::BONUS_VALUE_FIRST:
  307. bonusValue.first = val;
  308. break;
  309. case ObjProperty::BONUS_VALUE_SECOND:
  310. bonusValue.second = val;
  311. break;
  312. }
  313. }
  314. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  315. {
  316. if (hasBuilt(BuildingID::CASTLE))
  317. return CASTLE;
  318. if (hasBuilt(BuildingID::CITADEL))
  319. return CITADEL;
  320. if (hasBuilt(BuildingID::FORT))
  321. return FORT;
  322. return NONE;
  323. }
  324. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  325. {
  326. if (hasBuilt(BuildingID::CAPITOL))
  327. return 3;
  328. if (hasBuilt(BuildingID::CITY_HALL))
  329. return 2;
  330. if (hasBuilt(BuildingID::TOWN_HALL))
  331. return 1;
  332. if (hasBuilt(BuildingID::VILLAGE_HALL))
  333. return 0;
  334. return -1;
  335. }
  336. int CGTownInstance::mageGuildLevel() const
  337. {
  338. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  339. return 5;
  340. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  341. return 4;
  342. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  343. return 3;
  344. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  345. return 2;
  346. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  347. return 1;
  348. return 0;
  349. }
  350. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  351. {
  352. return town->hordeLvl.at(HID);
  353. }
  354. int CGTownInstance::creatureGrowth(const int & level) const
  355. {
  356. return getGrowthInfo(level).totalGrowth();
  357. }
  358. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  359. {
  360. GrowthInfo ret;
  361. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  362. return ret;
  363. if (creatures[level].second.empty())
  364. return ret; //no dwelling
  365. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  366. const int base = creature->growth;
  367. int castleBonus = 0;
  368. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  369. if (hasBuilt(BuildingID::CASTLE))
  370. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  371. else if (hasBuilt(BuildingID::CITADEL))
  372. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  373. if(town->hordeLvl.at(0) == level)//horde 1
  374. if(hasBuilt(BuildingID::HORDE_1))
  375. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  376. if(town->hordeLvl.at(1) == level)//horde 2
  377. if(hasBuilt(BuildingID::HORDE_2))
  378. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  379. int dwellingBonus = 0;
  380. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  381. {
  382. for(const CGDwelling *dwelling : p->dwellings)
  383. if(vstd::contains(creatures[level].second, dwelling->creatures[0].second[0]))
  384. dwellingBonus++;
  385. }
  386. if(dwellingBonus)
  387. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  388. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  389. TBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH).And(Selector::subtype(level)));
  390. for(const Bonus *b : *bonuses)
  391. ret.entries.push_back(GrowthInfo::Entry(b->val, b->Description()));
  392. //statue-of-legion-like bonus: % to base+castle
  393. TBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  394. for(const Bonus *b : *bonuses2)
  395. ret.entries.push_back(GrowthInfo::Entry(b->val * (base + castleBonus) / 100, b->Description()));
  396. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  397. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  398. return ret;
  399. }
  400. TResources CGTownInstance::dailyIncome() const
  401. {
  402. TResources ret;
  403. for (auto & p : town->buildings)
  404. {
  405. BuildingID buildingUpgrade;
  406. for (auto & p2 : town->buildings)
  407. {
  408. if (p2.second->upgrade == p.first)
  409. {
  410. buildingUpgrade = p2.first;
  411. }
  412. }
  413. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  414. {
  415. ret += p.second->produce;
  416. }
  417. }
  418. return ret;
  419. }
  420. bool CGTownInstance::hasFort() const
  421. {
  422. return hasBuilt(BuildingID::FORT);
  423. }
  424. bool CGTownInstance::hasCapitol() const
  425. {
  426. return hasBuilt(BuildingID::CAPITOL);
  427. }
  428. CGTownInstance::CGTownInstance()
  429. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  430. {
  431. }
  432. CGTownInstance::~CGTownInstance()
  433. {
  434. for (auto & elem : bonusingBuildings)
  435. delete elem;
  436. }
  437. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  438. {
  439. if(checkGuild && mageGuildLevel() < level)
  440. return 0;
  441. int ret = 6 - level; //how many spells are available at this level
  442. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  443. ret++;
  444. return ret;
  445. }
  446. bool CGTownInstance::needsLastStack() const
  447. {
  448. if(garrisonHero)
  449. return true;
  450. else return false;
  451. }
  452. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  453. {
  454. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  455. {
  456. if(armedGarrison() || visitingHero)
  457. {
  458. const CGHeroInstance *defendingHero = nullptr;
  459. const CArmedInstance *defendingArmy = this;
  460. if(visitingHero)
  461. defendingHero = visitingHero;
  462. else if(garrisonHero)
  463. defendingHero = garrisonHero;
  464. if(defendingHero)
  465. defendingArmy = defendingHero;
  466. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  467. //"borrowing" army from garrison to visiting hero
  468. if(!outsideTown && armedGarrison() &&
  469. visitingHero && defendingHero == visitingHero)
  470. {
  471. mergeGarrisonOnSiege();
  472. }
  473. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? nullptr : this));
  474. }
  475. else
  476. {
  477. cb->setOwner(this, h->tempOwner);
  478. removeCapitols(h->getOwner());
  479. cb->heroVisitCastle(this, h);
  480. }
  481. }
  482. else if(h->visitablePos() == visitablePos())
  483. {
  484. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  485. {
  486. SetCommanderProperty scp;
  487. scp.heroid = h->id;
  488. scp.which = SetCommanderProperty::ALIVE;
  489. scp.amount = 1;
  490. cb->sendAndApply (&scp);
  491. }
  492. cb->heroVisitCastle(this, h);
  493. }
  494. else
  495. {
  496. logGlobal->errorStream() << h->name << " visits allied town of " << name << " from different pos?";
  497. }
  498. }
  499. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  500. {
  501. //FIXME: find out why this issue appears on random maps
  502. if (visitingHero == h)
  503. {
  504. cb->stopHeroVisitCastle(this, h);
  505. //logGlobal->warnStream() << h->name << " correctly left town " << name;
  506. }
  507. else
  508. logGlobal->warnStream() << "Warning, " << h->name << " tries to leave the town " << name << " but hero is not inside.";
  509. }
  510. std::string CGTownInstance::getObjectName() const
  511. {
  512. return name + ", " + town->faction->name;
  513. }
  514. void CGTownInstance::initObj()
  515. ///initialize town structures
  516. {
  517. blockVisit = true;
  518. if (subID == ETownType::DUNGEON)
  519. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  520. else
  521. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  522. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  523. {
  524. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  525. int upgradeNum = 0;
  526. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  527. {
  528. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  529. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  530. }
  531. }
  532. switch (subID)
  533. { //add new visitable objects
  534. case 0:
  535. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  536. break;
  537. case 5:
  538. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  539. //fallthrough
  540. case 2: case 3: case 6:
  541. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  542. break;
  543. case 7:
  544. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  545. break;
  546. }
  547. //add special bonuses from buildings
  548. recreateBuildingsBonuses();
  549. updateAppearance();
  550. }
  551. void CGTownInstance::newTurn() const
  552. {
  553. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  554. {
  555. auto & rand = cb->gameState()->getRandomGenerator();
  556. //give resources for Rampart, Mystic Pond
  557. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  558. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  559. {
  560. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  561. resID = (resID==2)?1:resID;
  562. int resVal = rand.nextInt(1, 4);//with size 1..4
  563. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  564. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  565. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  566. }
  567. if ( subID == ETownType::DUNGEON )
  568. for (auto & elem : bonusingBuildings)
  569. {
  570. if ((elem)->ID == BuildingID::MANA_VORTEX)
  571. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (elem)->id); //reset visitors for Mana Vortex
  572. }
  573. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  574. {
  575. std::vector<SlotID> nativeCrits; //slots
  576. for (auto & elem : Slots())
  577. {
  578. if (elem.second->type->faction == subID) //native
  579. {
  580. nativeCrits.push_back(elem.first); //collect matching slots
  581. }
  582. }
  583. if (nativeCrits.size())
  584. {
  585. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  586. StackLocation sl(this, pos);
  587. const CCreature *c = getCreature(pos);
  588. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  589. {
  590. cb->changeStackCount(sl, c->growth);
  591. }
  592. else //upgrade
  593. {
  594. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  595. }
  596. }
  597. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  598. {
  599. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  600. if (!town->creatures[i].empty())
  601. {
  602. CreatureID c = town->creatures[i][0];
  603. SlotID n;
  604. TQuantity count = creatureGrowth(i);
  605. if (!count) // no dwelling
  606. count = VLC->creh->creatures[c]->growth;
  607. {//no lower tiers or above current month
  608. if ((n = getSlotFor(c)).validSlot())
  609. {
  610. StackLocation sl(this, n);
  611. if (slotEmpty(n))
  612. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  613. else //add to existing
  614. cb->changeStackCount(sl, count);
  615. }
  616. }
  617. }
  618. }
  619. }
  620. }
  621. }
  622. /*
  623. int3 CGTownInstance::getSightCenter() const
  624. {
  625. return pos - int3(2,0,0);
  626. }
  627. */
  628. bool CGTownInstance::passableFor(PlayerColor color) const
  629. {
  630. if (!armedGarrison())//empty castle - anyone can visit
  631. return true;
  632. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  633. return false;
  634. if (cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES)
  635. return true;
  636. return false;
  637. }
  638. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  639. {
  640. offsets = {int3(-1,2,0), int3(-3,2,0)};
  641. }
  642. void CGTownInstance::mergeGarrisonOnSiege() const
  643. {
  644. auto getWeakestStackSlot = [&](int powerLimit)
  645. {
  646. std::vector<SlotID> weakSlots;
  647. auto stacksList = visitingHero->stacks;
  648. std::pair<SlotID, CStackInstance *> pair;
  649. while(stacksList.size())
  650. {
  651. pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
  652. {
  653. return elem.second->getPower();
  654. });
  655. if(powerLimit > pair.second->getPower() &&
  656. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  657. {
  658. weakSlots.push_back(pair.first);
  659. stacksList.erase(pair.first);
  660. }
  661. else
  662. break;
  663. }
  664. if(weakSlots.size())
  665. return *std::max_element(weakSlots.begin(), weakSlots.end());
  666. return SlotID();
  667. };
  668. int count = stacks.size();
  669. for(int i = 0; i < count; i++)
  670. {
  671. auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
  672. {
  673. ui64 power = elem.second->getPower();
  674. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  675. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  676. power += visitingHero->getStack(dst).getPower();
  677. return power;
  678. });
  679. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  680. if(dst.validSlot())
  681. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  682. else
  683. {
  684. dst = getWeakestStackSlot(pair.second->getPower());
  685. if(dst.validSlot())
  686. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  687. }
  688. }
  689. }
  690. void CGTownInstance::removeCapitols (PlayerColor owner) const
  691. {
  692. if (hasCapitol()) // search if there's an older capitol
  693. {
  694. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  695. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  696. {
  697. if (*i != this && (*i)->hasCapitol())
  698. {
  699. RazeStructures rs;
  700. rs.tid = id;
  701. rs.bid.insert(BuildingID::CAPITOL);
  702. rs.destroyed = destroyed;
  703. cb->sendAndApply(&rs);
  704. return;
  705. }
  706. }
  707. }
  708. }
  709. void CGTownInstance::clearArmy() const
  710. {
  711. while(!stacks.empty())
  712. {
  713. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  714. }
  715. }
  716. int CGTownInstance::getBoatType() const
  717. {
  718. switch (town->faction->alignment)
  719. {
  720. case EAlignment::EVIL : return 0;
  721. case EAlignment::GOOD : return 1;
  722. case EAlignment::NEUTRAL : return 2;
  723. }
  724. assert(0);
  725. return -1;
  726. }
  727. int CGTownInstance::getMarketEfficiency() const
  728. {
  729. if (!hasBuilt(BuildingID::MARKETPLACE))
  730. return 0;
  731. const PlayerState *p = cb->getPlayer(tempOwner);
  732. assert(p);
  733. int marketCount = 0;
  734. for(const CGTownInstance *t : p->towns)
  735. if(t->hasBuilt(BuildingID::MARKETPLACE))
  736. marketCount++;
  737. return marketCount;
  738. }
  739. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  740. {
  741. switch(mode)
  742. {
  743. case EMarketMode::RESOURCE_RESOURCE:
  744. case EMarketMode::RESOURCE_PLAYER:
  745. return hasBuilt(BuildingID::MARKETPLACE);
  746. case EMarketMode::ARTIFACT_RESOURCE:
  747. case EMarketMode::RESOURCE_ARTIFACT:
  748. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  749. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  750. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  751. case EMarketMode::CREATURE_RESOURCE:
  752. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  753. case EMarketMode::CREATURE_UNDEAD:
  754. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  755. case EMarketMode::RESOURCE_SKILL:
  756. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  757. default:
  758. assert(0);
  759. return false;
  760. }
  761. }
  762. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  763. {
  764. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  765. {
  766. std::vector<int> ret;
  767. for(const CArtifact *a : merchantArtifacts)
  768. if(a)
  769. ret.push_back(a->id);
  770. else
  771. ret.push_back(-1);
  772. return ret;
  773. }
  774. else if ( mode == EMarketMode::RESOURCE_SKILL )
  775. {
  776. return universitySkills;
  777. }
  778. else
  779. return IMarket::availableItemsIds(mode);
  780. }
  781. void CGTownInstance::setType(si32 ID, si32 subID)
  782. {
  783. assert(ID == Obj::TOWN); // just in case
  784. CGObjectInstance::setType(ID, subID);
  785. town = VLC->townh->factions[subID]->town;
  786. randomizeArmy(subID);
  787. updateAppearance();
  788. }
  789. void CGTownInstance::updateAppearance()
  790. {
  791. //FIXME: not the best way to do this
  792. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  793. if (app)
  794. appearance = app.get();
  795. }
  796. std::string CGTownInstance::nodeName() const
  797. {
  798. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  799. }
  800. void CGTownInstance::deserializationFix()
  801. {
  802. attachTo(&townAndVis);
  803. //Hero is already handled by CGameState::attachArmedObjects
  804. // if(visitingHero)
  805. // visitingHero->attachTo(&townAndVis);
  806. // if(garrisonHero)
  807. // garrisonHero->attachTo(this);
  808. }
  809. void CGTownInstance::updateMoraleBonusFromArmy()
  810. {
  811. Bonus *b = getExportedBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  812. if(!b)
  813. {
  814. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  815. addNewBonus(b);
  816. }
  817. if (garrisonHero)
  818. {
  819. b->val = 0;
  820. CBonusSystemNode::treeHasChanged();
  821. }
  822. else
  823. CArmedInstance::updateMoraleBonusFromArmy();
  824. }
  825. void CGTownInstance::recreateBuildingsBonuses()
  826. {
  827. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  828. BonusList bl;
  829. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  830. for(Bonus *b : bl)
  831. removeBonus(b);
  832. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  833. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  834. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  835. if(subID == ETownType::CASTLE) //castle
  836. {
  837. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  838. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  839. }
  840. else if(subID == ETownType::RAMPART) //rampart
  841. {
  842. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  843. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  844. }
  845. else if(subID == ETownType::TOWER) //tower
  846. {
  847. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  848. }
  849. else if(subID == ETownType::INFERNO) //Inferno
  850. {
  851. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  852. }
  853. else if(subID == ETownType::NECROPOLIS) //necropolis
  854. {
  855. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  856. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  857. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  858. }
  859. else if(subID == ETownType::DUNGEON) //Dungeon
  860. {
  861. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  862. }
  863. else if(subID == ETownType::STRONGHOLD) //Stronghold
  864. {
  865. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  866. }
  867. else if(subID == ETownType::FORTRESS) //Fortress
  868. {
  869. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  870. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  871. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  872. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  873. }
  874. else if(subID == ETownType::CONFLUX)
  875. {
  876. }
  877. }
  878. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  879. {
  880. static auto emptyPropagator = TPropagatorPtr();
  881. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  882. }
  883. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype /*= -1*/)
  884. {
  885. if(hasBuilt(building))
  886. {
  887. std::ostringstream descr;
  888. descr << town->buildings.at(building)->Name() << " ";
  889. if(val > 0)
  890. descr << "+";
  891. else if(val < 0)
  892. descr << "-";
  893. descr << val;
  894. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  895. if(prop)
  896. b->addPropagator(prop);
  897. addNewBonus(b);
  898. return true;
  899. }
  900. return false;
  901. }
  902. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  903. {
  904. //if (!(!!visitingHero == !h))
  905. //{
  906. // logGlobal->warnStream() << boost::format("Hero visiting town %s is %s ") % name % (visitingHero.get() ? visitingHero->name : "NULL");
  907. // logGlobal->warnStream() << boost::format("New hero will be %s ") % (h ? h->name : "NULL");
  908. //
  909. //}
  910. assert(!!visitingHero == !h);
  911. if(h)
  912. {
  913. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  914. assert(p);
  915. h->detachFrom(p);
  916. h->attachTo(&townAndVis);
  917. visitingHero = h;
  918. h->visitedTown = this;
  919. h->inTownGarrison = false;
  920. }
  921. else
  922. {
  923. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  924. visitingHero->visitedTown = nullptr;
  925. visitingHero->detachFrom(&townAndVis);
  926. visitingHero->attachTo(p);
  927. visitingHero = nullptr;
  928. }
  929. }
  930. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  931. {
  932. assert(!!garrisonHero == !h);
  933. if(h)
  934. {
  935. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  936. assert(p);
  937. h->detachFrom(p);
  938. h->attachTo(this);
  939. garrisonHero = h;
  940. h->visitedTown = this;
  941. h->inTownGarrison = true;
  942. }
  943. else
  944. {
  945. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  946. garrisonHero->visitedTown = nullptr;
  947. garrisonHero->inTownGarrison = false;
  948. garrisonHero->detachFrom(this);
  949. garrisonHero->attachTo(p);
  950. garrisonHero = nullptr;
  951. }
  952. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  953. }
  954. bool CGTownInstance::armedGarrison() const
  955. {
  956. return stacksCount() || garrisonHero;
  957. }
  958. int CGTownInstance::getTownLevel() const
  959. {
  960. // count all buildings that are not upgrades
  961. return boost::range::count_if(builtBuildings, [&](const BuildingID & build)
  962. {
  963. return town->buildings.at(build) && town->buildings.at(build)->upgrade == -1;
  964. });
  965. }
  966. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  967. {
  968. return &townAndVis;
  969. }
  970. const CArmedInstance * CGTownInstance::getUpperArmy() const
  971. {
  972. if(garrisonHero)
  973. return garrisonHero;
  974. return this;
  975. }
  976. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  977. {
  978. if (townID == town->faction->index || townID == ETownType::ANY)
  979. return hasBuilt(buildingID);
  980. return false;
  981. }
  982. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  983. {
  984. return vstd::contains(builtBuildings, buildingID);
  985. }
  986. CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool includeUpgrade) const
  987. {
  988. const CBuilding * building = town->buildings.at(buildID);
  989. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  990. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  991. {
  992. const CBuilding * build = town->buildings.at(id);
  993. if (!hasBuilt(id))
  994. return id;
  995. if (build->upgrade != BuildingID::NONE && !hasBuilt(build->upgrade))
  996. return build->upgrade;
  997. return build->requirements.morph(dependTest);
  998. };
  999. CBuilding::TRequired::OperatorAll requirements;
  1000. if (building->upgrade != BuildingID::NONE)
  1001. {
  1002. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1003. if (includeUpgrade)
  1004. requirements.expressions.push_back(upgr->bid);
  1005. requirements.expressions.push_back(upgr->requirements.morph(dependTest));
  1006. }
  1007. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1008. CBuilding::TRequired::Variant variant(requirements);
  1009. CBuilding::TRequired ret(variant);
  1010. ret.minimize();
  1011. return ret;
  1012. }
  1013. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  1014. {
  1015. if(visitingHero == h)
  1016. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1017. else if(garrisonHero == h)
  1018. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1019. else
  1020. {
  1021. //should never ever happen
  1022. logGlobal->errorStream() << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID;
  1023. assert(0);
  1024. }
  1025. }
  1026. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1027. {
  1028. if(result.winner == 0)
  1029. {
  1030. clearArmy();
  1031. removeCapitols(hero->getOwner());
  1032. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  1033. FoWChange fw;
  1034. fw.player = hero->tempOwner;
  1035. fw.mode = 1;
  1036. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), tempOwner, 1);
  1037. cb->sendAndApply (&fw);
  1038. }
  1039. }
  1040. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  1041. {
  1042. ID = index;
  1043. town = TOWN;
  1044. id = town->bonusingBuildings.size();
  1045. }
  1046. void COPWBonus::setProperty(ui8 what, ui32 val)
  1047. {
  1048. switch (what)
  1049. {
  1050. case ObjProperty::VISITORS:
  1051. visitors.insert(val);
  1052. break;
  1053. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1054. visitors.clear();
  1055. break;
  1056. }
  1057. }
  1058. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  1059. {
  1060. ObjectInstanceID heroID = h->id;
  1061. if (town->hasBuilt(ID))
  1062. {
  1063. InfoWindow iw;
  1064. iw.player = h->tempOwner;
  1065. switch (town->subID)
  1066. {
  1067. case ETownType::CASTLE: //Stables
  1068. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1069. {
  1070. GiveBonus gb;
  1071. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  1072. gb.id = heroID.getNum();
  1073. cb->giveHeroBonus(&gb);
  1074. iw.text << VLC->generaltexth->allTexts[580];
  1075. cb->showInfoDialog(&iw);
  1076. }
  1077. break;
  1078. case ETownType::DUNGEON: //Mana Vortex
  1079. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  1080. {
  1081. cb->setManaPoints (heroID, 2 * h->manaLimit());
  1082. //TODO: investigate line below
  1083. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1084. iw.text << VLC->generaltexth->allTexts[579];
  1085. cb->showInfoDialog(&iw);
  1086. town->addHeroToStructureVisitors(h, id);
  1087. }
  1088. break;
  1089. }
  1090. }
  1091. }
  1092. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  1093. {
  1094. ID = index;
  1095. town = TOWN;
  1096. id = town->bonusingBuildings.size();
  1097. }
  1098. void CTownBonus::setProperty (ui8 what, ui32 val)
  1099. {
  1100. if(what == ObjProperty::VISITORS)
  1101. visitors.insert(ObjectInstanceID(val));
  1102. }
  1103. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1104. {
  1105. ObjectInstanceID heroID = h->id;
  1106. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  1107. {
  1108. InfoWindow iw;
  1109. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  1110. int val=0, mid=0;
  1111. switch (ID)
  1112. {
  1113. case BuildingID::SPECIAL_4:
  1114. switch(town->subID)
  1115. {
  1116. case ETownType::TOWER: //wall
  1117. what = PrimarySkill::KNOWLEDGE;
  1118. val = 1;
  1119. mid = 581;
  1120. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  1121. break;
  1122. case ETownType::INFERNO: //order of fire
  1123. what = PrimarySkill::SPELL_POWER;
  1124. val = 1;
  1125. mid = 582;
  1126. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  1127. break;
  1128. case ETownType::STRONGHOLD://hall of Valhalla
  1129. what = PrimarySkill::ATTACK;
  1130. val = 1;
  1131. mid = 584;
  1132. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  1133. break;
  1134. case ETownType::DUNGEON://academy of battle scholars
  1135. what = PrimarySkill::EXPERIENCE;
  1136. val = h->calculateXp(1000);
  1137. mid = 583;
  1138. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  1139. break;
  1140. }
  1141. break;
  1142. case BuildingID::SPECIAL_1:
  1143. switch(town->subID)
  1144. {
  1145. case ETownType::FORTRESS: //cage of warlords
  1146. what = PrimarySkill::DEFENSE;
  1147. val = 1;
  1148. mid = 585;
  1149. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  1150. break;
  1151. }
  1152. break;
  1153. }
  1154. assert(mid);
  1155. iw.player = cb->getOwner(heroID);
  1156. iw.text << VLC->generaltexth->allTexts[mid];
  1157. cb->showInfoDialog(&iw);
  1158. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1159. town->addHeroToStructureVisitors(h, id);
  1160. }
  1161. }
  1162. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1163. : count(_count)
  1164. {
  1165. description = boost::str(boost::format(format) % count);
  1166. }
  1167. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  1168. : count(_count)
  1169. {
  1170. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  1171. }
  1172. GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
  1173. : count(_count)
  1174. {
  1175. description = fullDescription;
  1176. }
  1177. CTownAndVisitingHero::CTownAndVisitingHero()
  1178. {
  1179. setNodeType(TOWN_AND_VISITOR);
  1180. }
  1181. int GrowthInfo::totalGrowth() const
  1182. {
  1183. int ret = 0;
  1184. for(const Entry &entry : entries)
  1185. ret += entry.count;
  1186. return ret;
  1187. }