CGTownInstance.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  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 "../spells/CSpellHandler.h"
  14. #include "../NetPacks.h"
  15. #include "../CGeneralTextHandler.h"
  16. #include "../CModHandler.h"
  17. #include "../IGameCallback.h"
  18. #include "../CGameState.h"
  19. #include "../mapping/CMap.h"
  20. #include "../CPlayerState.h"
  21. #include "../serializer/JsonSerializeFormat.h"
  22. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  23. std::vector<int> CGTownInstance::universitySkills;
  24. CSpecObjInfo::CSpecObjInfo():
  25. owner(nullptr)
  26. {
  27. }
  28. CCreGenAsCastleInfo::CCreGenAsCastleInfo():
  29. CSpecObjInfo(), asCastle(false),identifier(0)
  30. {
  31. }
  32. void CCreGenAsCastleInfo::serializeJson(JsonSerializeFormat & handler)
  33. {
  34. handler.serializeString("sameAsTown", instanceId);
  35. if(!handler.saving)
  36. {
  37. asCastle = (instanceId != "");
  38. allowedFactions.clear();
  39. }
  40. if(!asCastle)
  41. {
  42. std::vector<bool> standard;
  43. standard.resize(VLC->townh->factions.size(), true);
  44. JsonSerializeFormat::LIC allowedLIC(standard, &CTownHandler::decodeFaction, &CTownHandler::encodeFaction);
  45. allowedLIC.any = allowedFactions;
  46. handler.serializeLIC("allowedFactions", allowedLIC);
  47. if(!handler.saving)
  48. {
  49. allowedFactions = allowedLIC.any;
  50. }
  51. }
  52. }
  53. CCreGenLeveledInfo::CCreGenLeveledInfo():
  54. CSpecObjInfo(),
  55. minLevel(0), maxLevel(7)
  56. {
  57. }
  58. void CCreGenLeveledInfo::serializeJson(JsonSerializeFormat & handler)
  59. {
  60. handler.serializeInt("minLevel", minLevel, ui8(1));
  61. handler.serializeInt("maxLevel", maxLevel, ui8(7));
  62. if(!handler.saving)
  63. {
  64. //todo: safely allow any level > 7
  65. vstd::amax(minLevel, 1);
  66. vstd::amin(minLevel, 7);
  67. vstd::abetween(maxLevel, minLevel, 7);
  68. }
  69. }
  70. void CCreGenLeveledCastleInfo::serializeJson(JsonSerializeFormat & handler)
  71. {
  72. CCreGenAsCastleInfo::serializeJson(handler);
  73. CCreGenLeveledInfo::serializeJson(handler);
  74. }
  75. CGDwelling::CGDwelling():
  76. CArmedInstance()
  77. {
  78. info = nullptr;
  79. }
  80. CGDwelling::~CGDwelling()
  81. {
  82. vstd::clear_pointer(info);
  83. }
  84. void CGDwelling::initObj(CRandomGenerator & rand)
  85. {
  86. switch(ID)
  87. {
  88. case Obj::CREATURE_GENERATOR1:
  89. case Obj::CREATURE_GENERATOR4:
  90. {
  91. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  92. if (getOwner() != PlayerColor::NEUTRAL)
  93. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  94. assert(!creatures.empty());
  95. assert(!creatures[0].second.empty());
  96. break;
  97. }
  98. case Obj::REFUGEE_CAMP:
  99. //is handled within newturn func
  100. break;
  101. case Obj::WAR_MACHINE_FACTORY:
  102. creatures.resize(3);
  103. creatures[0].second.push_back(CreatureID::BALLISTA);
  104. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  105. creatures[2].second.push_back(CreatureID::AMMO_CART);
  106. break;
  107. default:
  108. assert(0);
  109. break;
  110. }
  111. }
  112. void CGDwelling::initRandomObjectInfo()
  113. {
  114. vstd::clear_pointer(info);
  115. switch(ID)
  116. {
  117. case Obj::RANDOM_DWELLING: info = new CCreGenLeveledCastleInfo();
  118. break;
  119. case Obj::RANDOM_DWELLING_LVL: info = new CCreGenAsCastleInfo();
  120. break;
  121. case Obj::RANDOM_DWELLING_FACTION: info = new CCreGenLeveledInfo();
  122. break;
  123. }
  124. if(info)
  125. info->owner = this;
  126. }
  127. void CGDwelling::setPropertyDer(ui8 what, ui32 val)
  128. {
  129. switch (what)
  130. {
  131. case ObjProperty::OWNER: //change owner
  132. if (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR2
  133. || ID == Obj::CREATURE_GENERATOR3 || ID == Obj::CREATURE_GENERATOR4)
  134. {
  135. if (tempOwner != PlayerColor::NEUTRAL)
  136. {
  137. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  138. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  139. }
  140. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  141. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  142. }
  143. break;
  144. case ObjProperty::AVAILABLE_CREATURE:
  145. creatures.resize(1);
  146. creatures[0].second.resize(1);
  147. creatures[0].second[0] = CreatureID(val);
  148. break;
  149. }
  150. }
  151. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  152. {
  153. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  154. {
  155. InfoWindow iw;
  156. iw.player = h->tempOwner;
  157. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  158. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  159. cb->sendAndApply(&iw);
  160. return;
  161. }
  162. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  163. if ( relations == PlayerRelations::ALLIES )
  164. return;//do not allow recruiting or capturing
  165. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  166. {
  167. BlockingDialog bd(true,false);
  168. bd.player = h->tempOwner;
  169. 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?
  170. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  171. bd.text.addReplacement(MetaString::ARRAY_TXT, 173 + Slots().begin()->second->getQuantityID()*3);
  172. bd.text.addReplacement(*Slots().begin()->second);
  173. cb->showBlockingDialog(&bd);
  174. return;
  175. }
  176. // TODO this shouldn't be hardcoded
  177. if(!relations && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  178. {
  179. cb->setOwner(this, h->tempOwner);
  180. }
  181. BlockingDialog bd (true,false);
  182. bd.player = h->tempOwner;
  183. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  184. {
  185. 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?
  186. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  187. for(auto & elem : creatures)
  188. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  189. }
  190. else if(ID == Obj::REFUGEE_CAMP)
  191. {
  192. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  193. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  194. for(auto & elem : creatures)
  195. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  196. }
  197. else if(ID == Obj::WAR_MACHINE_FACTORY)
  198. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  199. else
  200. throw std::runtime_error("Illegal dwelling!");
  201. cb->showBlockingDialog(&bd);
  202. }
  203. void CGDwelling::newTurn(CRandomGenerator & rand) const
  204. {
  205. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  206. return;
  207. //town growths and War Machines Factories are handled separately
  208. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  209. return;
  210. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  211. {
  212. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
  213. }
  214. bool change = false;
  215. SetAvailableCreatures sac;
  216. sac.creatures = creatures;
  217. sac.tid = id;
  218. for (size_t i = 0; i < creatures.size(); i++)
  219. {
  220. if(creatures[i].second.size())
  221. {
  222. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  223. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  224. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  225. sac.creatures[i].first += amount;
  226. else
  227. sac.creatures[i].first = amount;
  228. change = true;
  229. }
  230. }
  231. if(change)
  232. cb->sendAndApply(&sac);
  233. updateGuards();
  234. }
  235. void CGDwelling::updateGuards() const
  236. {
  237. //TODO: store custom guard config and use it
  238. //TODO: store boolean flag for guards
  239. bool guarded = false;
  240. //default condition - creatures are of level 5 or higher
  241. for (auto creatureEntry : creatures)
  242. {
  243. if (VLC->creh->creatures[creatureEntry.second.at(0)]->level >= 5 && ID != Obj::REFUGEE_CAMP)
  244. {
  245. guarded = true;
  246. break;
  247. }
  248. }
  249. if (guarded)
  250. {
  251. for (auto creatureEntry : creatures)
  252. {
  253. const CCreature * crea = VLC->creh->creatures[creatureEntry.second.at(0)];
  254. SlotID slot = getSlotFor(crea->idNumber);
  255. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  256. {
  257. ChangeStackCount csc;
  258. csc.army = this->id;
  259. csc.slot = slot;
  260. csc.count = crea->growth * 3;
  261. csc.absoluteValue = true;
  262. cb->sendAndApply(&csc);
  263. }
  264. else //slot is empty, create whole new stack
  265. {
  266. InsertNewStack ns;
  267. ns.army = this->id;
  268. ns.slot = slot;
  269. ns.type = crea->idNumber;
  270. ns.count = crea->growth * 3;
  271. cb->sendAndApply(&ns);
  272. }
  273. }
  274. }
  275. }
  276. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  277. {
  278. CreatureID crid = creatures[0].second[0];
  279. CCreature *crs = VLC->creh->creatures[crid];
  280. TQuantity count = creatures[0].first;
  281. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  282. {
  283. if(count) //there are available creatures
  284. {
  285. SlotID slot = h->getSlotFor(crid);
  286. if(!slot.validSlot()) //no available slot
  287. {
  288. InfoWindow iw;
  289. iw.player = h->tempOwner;
  290. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  291. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  292. cb->showInfoDialog(&iw);
  293. }
  294. else //give creatures
  295. {
  296. SetAvailableCreatures sac;
  297. sac.tid = id;
  298. sac.creatures = creatures;
  299. sac.creatures[0].first = 0;
  300. InfoWindow iw;
  301. iw.player = h->tempOwner;
  302. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  303. iw.text.addReplacement(count);
  304. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  305. cb->showInfoDialog(&iw);
  306. cb->sendAndApply(&sac);
  307. cb->addToSlot(StackLocation(h, slot), crs, count);
  308. }
  309. }
  310. else //there no creatures
  311. {
  312. InfoWindow iw;
  313. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  314. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  315. iw.player = h->tempOwner;
  316. cb->sendAndApply(&iw);
  317. }
  318. }
  319. else
  320. {
  321. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  322. {
  323. //there is 1 war machine available to recruit if hero doesn't have one
  324. SetAvailableCreatures sac;
  325. sac.tid = id;
  326. sac.creatures = creatures;
  327. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  328. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  329. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  330. cb->sendAndApply(&sac);
  331. }
  332. OpenWindow ow;
  333. ow.id1 = id.getNum();
  334. ow.id2 = h->id.getNum();
  335. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  336. ? OpenWindow::RECRUITMENT_FIRST
  337. : OpenWindow::RECRUITMENT_ALL;
  338. cb->sendAndApply(&ow);
  339. }
  340. }
  341. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  342. {
  343. if (result.winner == 0)
  344. {
  345. onHeroVisit(hero);
  346. }
  347. }
  348. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  349. {
  350. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  351. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  352. {
  353. if(answer)
  354. cb->startBattleI(hero, this);
  355. }
  356. else if(answer)
  357. {
  358. heroAcceptsCreatures(hero);
  359. }
  360. }
  361. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  362. {
  363. if(!handler.saving)
  364. initRandomObjectInfo();
  365. switch (ID)
  366. {
  367. case Obj::WAR_MACHINE_FACTORY:
  368. case Obj::REFUGEE_CAMP:
  369. //do nothing
  370. break;
  371. case Obj::RANDOM_DWELLING:
  372. case Obj::RANDOM_DWELLING_LVL:
  373. case Obj::RANDOM_DWELLING_FACTION:
  374. info->serializeJson(handler);
  375. //fall through
  376. default:
  377. serializeJsonOwner(handler);
  378. break;
  379. }
  380. }
  381. TPropagatorPtr CGTownInstance::emptyPropagator = TPropagatorPtr();
  382. int CGTownInstance::getSightRadius() const //returns sight distance
  383. {
  384. auto ret = CBuilding::HEIGHT_NO_TOWER;
  385. for(const auto & bid : builtBuildings)
  386. {
  387. if(bid.IsSpecialOrGrail())
  388. {
  389. auto height = town->buildings.at(bid)->height;
  390. if(ret < height)
  391. ret = height;
  392. }
  393. }
  394. return ret;
  395. }
  396. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  397. {
  398. ///this is freakin' overcomplicated solution
  399. switch (what)
  400. {
  401. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  402. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  403. break;
  404. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  405. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  406. break;
  407. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  408. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  409. break;
  410. case ObjProperty::BONUS_VALUE_FIRST:
  411. bonusValue.first = val;
  412. break;
  413. case ObjProperty::BONUS_VALUE_SECOND:
  414. bonusValue.second = val;
  415. break;
  416. }
  417. }
  418. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  419. {
  420. if (hasBuilt(BuildingID::CASTLE))
  421. return CASTLE;
  422. if (hasBuilt(BuildingID::CITADEL))
  423. return CITADEL;
  424. if (hasBuilt(BuildingID::FORT))
  425. return FORT;
  426. return NONE;
  427. }
  428. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  429. {
  430. if (hasBuilt(BuildingID::CAPITOL))
  431. return 3;
  432. if (hasBuilt(BuildingID::CITY_HALL))
  433. return 2;
  434. if (hasBuilt(BuildingID::TOWN_HALL))
  435. return 1;
  436. if (hasBuilt(BuildingID::VILLAGE_HALL))
  437. return 0;
  438. return -1;
  439. }
  440. int CGTownInstance::mageGuildLevel() const
  441. {
  442. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  443. return 5;
  444. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  445. return 4;
  446. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  447. return 3;
  448. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  449. return 2;
  450. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  451. return 1;
  452. return 0;
  453. }
  454. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  455. {
  456. return town->hordeLvl.at(HID);
  457. }
  458. int CGTownInstance::creatureGrowth(const int & level) const
  459. {
  460. return getGrowthInfo(level).totalGrowth();
  461. }
  462. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  463. {
  464. GrowthInfo ret;
  465. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  466. return ret;
  467. if (creatures[level].second.empty())
  468. return ret; //no dwelling
  469. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  470. const int base = creature->growth;
  471. int castleBonus = 0;
  472. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  473. if (hasBuilt(BuildingID::CASTLE))
  474. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  475. else if (hasBuilt(BuildingID::CITADEL))
  476. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  477. if(town->hordeLvl.at(0) == level)//horde 1
  478. if(hasBuilt(BuildingID::HORDE_1))
  479. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  480. if(town->hordeLvl.at(1) == level)//horde 2
  481. if(hasBuilt(BuildingID::HORDE_2))
  482. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  483. int dwellingBonus = 0;
  484. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  485. {
  486. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  487. }
  488. if(dwellingBonus)
  489. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  490. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  491. TConstBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH).And(Selector::subtype(level)));
  492. for(const auto & b : *bonuses)
  493. ret.entries.push_back(GrowthInfo::Entry(b->val, b->Description()));
  494. //statue-of-legion-like bonus: % to base+castle
  495. TConstBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  496. for(const auto & b : *bonuses2)
  497. ret.entries.push_back(GrowthInfo::Entry(b->val * (base + castleBonus) / 100, b->Description()));
  498. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  499. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  500. return ret;
  501. }
  502. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  503. {
  504. int totalBonus = 0;
  505. for (const auto& dwelling : dwellings)
  506. {
  507. for (const auto& creature : dwelling->creatures)
  508. {
  509. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  510. }
  511. }
  512. return totalBonus;
  513. }
  514. TResources CGTownInstance::dailyIncome() const
  515. {
  516. TResources ret;
  517. for (auto & p : town->buildings)
  518. {
  519. BuildingID buildingUpgrade;
  520. for (auto & p2 : town->buildings)
  521. {
  522. if (p2.second->upgrade == p.first)
  523. {
  524. buildingUpgrade = p2.first;
  525. }
  526. }
  527. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  528. {
  529. ret += p.second->produce;
  530. }
  531. }
  532. return ret;
  533. }
  534. bool CGTownInstance::hasFort() const
  535. {
  536. return hasBuilt(BuildingID::FORT);
  537. }
  538. bool CGTownInstance::hasCapitol() const
  539. {
  540. return hasBuilt(BuildingID::CAPITOL);
  541. }
  542. CGTownInstance::CGTownInstance()
  543. :CGDwelling(), IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  544. {
  545. }
  546. CGTownInstance::~CGTownInstance()
  547. {
  548. for (auto & elem : bonusingBuildings)
  549. delete elem;
  550. }
  551. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  552. {
  553. if(checkGuild && mageGuildLevel() < level)
  554. return 0;
  555. int ret = 6 - level; //how many spells are available at this level
  556. if (hasBuilt(BuildingSubID::LIBRARY))
  557. ret++;
  558. return ret;
  559. }
  560. bool CGTownInstance::needsLastStack() const
  561. {
  562. if(garrisonHero)
  563. return true;
  564. else return false;
  565. }
  566. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  567. {
  568. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  569. {
  570. if(armedGarrison() || visitingHero)
  571. {
  572. const CGHeroInstance *defendingHero = nullptr;
  573. const CArmedInstance *defendingArmy = this;
  574. if(visitingHero)
  575. defendingHero = visitingHero;
  576. else if(garrisonHero)
  577. defendingHero = garrisonHero;
  578. if(defendingHero)
  579. defendingArmy = defendingHero;
  580. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  581. //"borrowing" army from garrison to visiting hero
  582. if(!outsideTown && armedGarrison() &&
  583. visitingHero && defendingHero == visitingHero)
  584. {
  585. mergeGarrisonOnSiege();
  586. }
  587. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? nullptr : this));
  588. }
  589. else
  590. {
  591. cb->setOwner(this, h->tempOwner);
  592. if(cb->gameState()->getPlayerStatus(h->getOwner()) == EPlayerStatus::WINNER)
  593. {
  594. return; //we just won game, we do not need to perform any extra actions
  595. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  596. }
  597. removeCapitols(h->getOwner());
  598. cb->heroVisitCastle(this, h);
  599. }
  600. }
  601. else if(h->visitablePos() == visitablePos())
  602. {
  603. bool commander_recover = h->commander && !h->commander->alive;
  604. if (commander_recover) // rise commander from dead
  605. {
  606. SetCommanderProperty scp;
  607. scp.heroid = h->id;
  608. scp.which = SetCommanderProperty::ALIVE;
  609. scp.amount = 1;
  610. cb->sendAndApply(&scp);
  611. }
  612. cb->heroVisitCastle(this, h);
  613. // TODO(vmarkovtsev): implement payment for rising the commander
  614. if (commander_recover) // info window about commander
  615. {
  616. InfoWindow iw;
  617. iw.player = h->tempOwner;
  618. iw.text << h->commander->getName();
  619. iw.components.push_back(Component(*h->commander));
  620. cb->showInfoDialog(&iw);
  621. }
  622. }
  623. else
  624. {
  625. logGlobal->error("%s visits allied town of %s from different pos?", h->name, name);
  626. }
  627. }
  628. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  629. {
  630. //FIXME: find out why this issue appears on random maps
  631. if(visitingHero == h)
  632. {
  633. cb->stopHeroVisitCastle(this, h);
  634. logGlobal->trace("%s correctly left town %s", h->name, name);
  635. }
  636. else
  637. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->name, name);
  638. }
  639. std::string CGTownInstance::getObjectName() const
  640. {
  641. return name + ", " + town->faction->name;
  642. }
  643. bool CGTownInstance::townEnvisagesSpecialBuilding(BuildingSubID::EBuildingSubID bid) const
  644. {
  645. for(const auto & it : town->buildings)
  646. {
  647. if(it.second->subId == bid)
  648. return true;
  649. }
  650. return false;
  651. }
  652. void CGTownInstance::initObj(CRandomGenerator & rand)
  653. ///initialize town structures
  654. {
  655. blockVisit = true;
  656. if(townEnvisagesSpecialBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  657. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);
  658. else
  659. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  660. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  661. {
  662. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  663. int upgradeNum = 0;
  664. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  665. {
  666. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  667. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  668. }
  669. }
  670. if(townEnvisagesSpecialBuilding(BuildingSubID::STABLES))
  671. bonusingBuildings.push_back(new COPWBonus(BuildingID::STABLES, BuildingSubID::STABLES, this));
  672. if(townEnvisagesSpecialBuilding(BuildingSubID::MANA_VORTEX))
  673. bonusingBuildings.push_back(new COPWBonus(BuildingID::MANA_VORTEX, BuildingSubID::MANA_VORTEX, this));
  674. switch (subID)
  675. {
  676. //add new visitable objects
  677. case ETownType::DUNGEON:
  678. case ETownType::TOWER:
  679. case ETownType::INFERNO:
  680. case ETownType::STRONGHOLD:
  681. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  682. break;
  683. case ETownType::FORTRESS:
  684. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  685. break;
  686. }
  687. //add special bonuses from buildings
  688. recreateBuildingsBonuses();
  689. updateAppearance();
  690. }
  691. void CGTownInstance::updateBonusingBuildings()
  692. {
  693. if (this->town->faction != nullptr)
  694. {
  695. //firstly, update subtype for the Bonusing objects, which are already stored in the bonusing list
  696. for (auto building : bonusingBuildings)
  697. {
  698. switch (this->town->faction->index)
  699. {
  700. case ETownType::CASTLE:
  701. if (building->getBuildingType() == BuildingID::SPECIAL_2)
  702. building->setBuildingSubtype(BuildingSubID::STABLES);
  703. break;
  704. case ETownType::DUNGEON:
  705. if(building->getBuildingType() == BuildingID::SPECIAL_2)
  706. building->setBuildingSubtype(BuildingSubID::MANA_VORTEX);
  707. break;
  708. }
  709. }
  710. }
  711. //secondly, supplement bonusing buildings list and active bonuses; subtypes for these objects are already set in update792
  712. for (auto & kvp : town->buildings)
  713. {
  714. auto & building = kvp.second;
  715. switch (building->subId)
  716. {
  717. case BuildingSubID::PORTAL_OF_SUMMONING:
  718. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  719. break;
  720. ///'hasBuilt' checking for COPW bonuses is in the COPWBonus::onHeroVisit
  721. case BuildingSubID::STABLES:
  722. if(getBonusingBuilding(building->subId) == nullptr)
  723. bonusingBuildings.push_back(new COPWBonus(BuildingID::STABLES, BuildingSubID::STABLES, this));
  724. break;
  725. case BuildingSubID::MANA_VORTEX:
  726. if(getBonusingBuilding(building->subId) == nullptr)
  727. bonusingBuildings.push_back(new COPWBonus(BuildingID::MANA_VORTEX, BuildingSubID::MANA_VORTEX, this));
  728. break;
  729. ///add new bonus if bonusing building was built in the user added towns:
  730. case BuildingSubID::BROTHERHOOD_OF_SWORD:
  731. if(!hasBuiltInOldWay(ETownType::CASTLE, BuildingID::BROTHERHOOD))
  732. addBonusIfBuilt(BuildingID::BROTHERHOOD, BuildingSubID::BROTHERHOOD_OF_SWORD, Bonus::MORALE, +2);
  733. break;
  734. case BuildingSubID::FOUNTAIN_OF_FORTUNE:
  735. if(!hasBuiltInOldWay(ETownType::RAMPART, BuildingID::FOUNTAIN_OF_FORTUNE))
  736. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, BuildingSubID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2);
  737. break;
  738. case BuildingSubID::SPELL_POWER_GARRISON_BONUS:
  739. if(!hasBuiltInOldWay(ETownType::INFERNO, BuildingID::STORMCLOUDS))
  740. addBonusIfBuilt(BuildingID::STORMCLOUDS, BuildingSubID::SPELL_POWER_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER);
  741. break;
  742. case BuildingSubID::ATTACK_GARRISON_BONUS:
  743. if(!hasBuiltInOldWay(ETownType::FORTRESS, BuildingID::BLOOD_OBELISK))
  744. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, BuildingSubID::ATTACK_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK);
  745. break;
  746. case BuildingSubID::DEFENSE_GARRISON_BONUS:
  747. if(!hasBuiltInOldWay(ETownType::FORTRESS, BuildingID::GLYPHS_OF_FEAR))
  748. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, BuildingSubID::DEFENSE_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE);
  749. break;
  750. }
  751. }
  752. }
  753. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, BuildingID bid) const
  754. {
  755. return (this->town->faction != nullptr && this->town->faction->index == type && hasBuilt(bid));
  756. }
  757. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  758. {
  759. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  760. {
  761. //give resources if there's a Mystic Pond
  762. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  763. && cb->getDate(Date::DAY) != 1
  764. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  765. )
  766. {
  767. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  768. resID = (resID==2)?1:resID;
  769. int resVal = rand.nextInt(1, 4);//with size 1..4
  770. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  771. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  772. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  773. }
  774. auto manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  775. if (manaVortex != nullptr)
  776. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  777. //get Mana Vortex or Stables bonuses
  778. //same code is in the CGameHandler::buildStructure method
  779. if (visitingHero != nullptr)
  780. cb->visitCastleObjects(this, visitingHero);
  781. if (garrisonHero != nullptr)
  782. cb->visitCastleObjects(this, garrisonHero);
  783. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  784. {
  785. std::vector<SlotID> nativeCrits; //slots
  786. for (auto & elem : Slots())
  787. {
  788. if (elem.second->type->faction == subID) //native
  789. {
  790. nativeCrits.push_back(elem.first); //collect matching slots
  791. }
  792. }
  793. if (nativeCrits.size())
  794. {
  795. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  796. StackLocation sl(this, pos);
  797. const CCreature *c = getCreature(pos);
  798. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  799. {
  800. cb->changeStackCount(sl, c->growth);
  801. }
  802. else //upgrade
  803. {
  804. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  805. }
  806. }
  807. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  808. {
  809. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  810. if (!town->creatures[i].empty())
  811. {
  812. CreatureID c = town->creatures[i][0];
  813. SlotID n;
  814. TQuantity count = creatureGrowth(i);
  815. if (!count) // no dwelling
  816. count = VLC->creh->creatures[c]->growth;
  817. {//no lower tiers or above current month
  818. if ((n = getSlotFor(c)).validSlot())
  819. {
  820. StackLocation sl(this, n);
  821. if (slotEmpty(n))
  822. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  823. else //add to existing
  824. cb->changeStackCount(sl, count);
  825. }
  826. }
  827. }
  828. }
  829. }
  830. }
  831. }
  832. /*
  833. int3 CGTownInstance::getSightCenter() const
  834. {
  835. return pos - int3(2,0,0);
  836. }
  837. */
  838. bool CGTownInstance::passableFor(PlayerColor color) const
  839. {
  840. if (!armedGarrison())//empty castle - anyone can visit
  841. return true;
  842. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  843. return false;
  844. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  845. }
  846. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  847. {
  848. offsets = {int3(-1,2,0), int3(-3,2,0)};
  849. }
  850. void CGTownInstance::mergeGarrisonOnSiege() const
  851. {
  852. auto getWeakestStackSlot = [&](ui64 powerLimit)
  853. {
  854. std::vector<SlotID> weakSlots;
  855. auto stacksList = visitingHero->stacks;
  856. std::pair<SlotID, CStackInstance *> pair;
  857. while(stacksList.size())
  858. {
  859. pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
  860. {
  861. return elem.second->getPower();
  862. });
  863. if(powerLimit > pair.second->getPower() &&
  864. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  865. {
  866. weakSlots.push_back(pair.first);
  867. stacksList.erase(pair.first);
  868. }
  869. else
  870. break;
  871. }
  872. if(weakSlots.size())
  873. return *std::max_element(weakSlots.begin(), weakSlots.end());
  874. return SlotID();
  875. };
  876. auto count = static_cast<int>(stacks.size());
  877. for(int i = 0; i < count; i++)
  878. {
  879. auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
  880. {
  881. ui64 power = elem.second->getPower();
  882. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  883. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  884. power += visitingHero->getStack(dst).getPower();
  885. return power;
  886. });
  887. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  888. if(dst.validSlot())
  889. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  890. else
  891. {
  892. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  893. if(dst.validSlot())
  894. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  895. }
  896. }
  897. }
  898. void CGTownInstance::removeCapitols (PlayerColor owner) const
  899. {
  900. if (hasCapitol()) // search if there's an older capitol
  901. {
  902. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  903. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  904. {
  905. if (*i != this && (*i)->hasCapitol())
  906. {
  907. RazeStructures rs;
  908. rs.tid = id;
  909. rs.bid.insert(BuildingID::CAPITOL);
  910. rs.destroyed = destroyed;
  911. cb->sendAndApply(&rs);
  912. return;
  913. }
  914. }
  915. }
  916. }
  917. void CGTownInstance::clearArmy() const
  918. {
  919. while(!stacks.empty())
  920. {
  921. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  922. }
  923. }
  924. int CGTownInstance::getBoatType() const
  925. {
  926. switch (town->faction->alignment)
  927. {
  928. case EAlignment::EVIL : return 0;
  929. case EAlignment::GOOD : return 1;
  930. case EAlignment::NEUTRAL : return 2;
  931. }
  932. assert(0);
  933. return -1;
  934. }
  935. int CGTownInstance::getMarketEfficiency() const
  936. {
  937. if (!hasBuilt(BuildingID::MARKETPLACE))
  938. return 0;
  939. const PlayerState *p = cb->getPlayer(tempOwner);
  940. assert(p);
  941. int marketCount = 0;
  942. for(const CGTownInstance *t : p->towns)
  943. if(t->hasBuilt(BuildingID::MARKETPLACE))
  944. marketCount++;
  945. return marketCount;
  946. }
  947. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  948. {
  949. switch(mode)
  950. {
  951. case EMarketMode::RESOURCE_RESOURCE:
  952. case EMarketMode::RESOURCE_PLAYER:
  953. return hasBuilt(BuildingID::MARKETPLACE);
  954. case EMarketMode::ARTIFACT_RESOURCE:
  955. case EMarketMode::RESOURCE_ARTIFACT:
  956. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  957. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  958. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  959. case EMarketMode::CREATURE_RESOURCE:
  960. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  961. case EMarketMode::CREATURE_UNDEAD:
  962. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  963. case EMarketMode::RESOURCE_SKILL:
  964. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  965. default:
  966. assert(0);
  967. return false;
  968. }
  969. }
  970. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  971. {
  972. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  973. {
  974. std::vector<int> ret;
  975. for(const CArtifact *a : merchantArtifacts)
  976. if(a)
  977. ret.push_back(a->id);
  978. else
  979. ret.push_back(-1);
  980. return ret;
  981. }
  982. else if ( mode == EMarketMode::RESOURCE_SKILL )
  983. {
  984. return universitySkills;
  985. }
  986. else
  987. return IMarket::availableItemsIds(mode);
  988. }
  989. void CGTownInstance::setType(si32 ID, si32 subID)
  990. {
  991. assert(ID == Obj::TOWN); // just in case
  992. CGObjectInstance::setType(ID, subID);
  993. town = VLC->townh->factions[subID]->town;
  994. randomizeArmy(subID);
  995. updateAppearance();
  996. }
  997. void CGTownInstance::updateAppearance()
  998. {
  999. //FIXME: not the best way to do this
  1000. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  1001. if (app)
  1002. appearance = app.get();
  1003. }
  1004. std::string CGTownInstance::nodeName() const
  1005. {
  1006. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  1007. }
  1008. void CGTownInstance::deserializationFix()
  1009. {
  1010. attachTo(&townAndVis);
  1011. //Hero is already handled by CGameState::attachArmedObjects
  1012. // if(visitingHero)
  1013. // visitingHero->attachTo(&townAndVis);
  1014. // if(garrisonHero)
  1015. // garrisonHero->attachTo(this);
  1016. }
  1017. void CGTownInstance::updateMoraleBonusFromArmy()
  1018. {
  1019. auto b = getExportedBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  1020. if(!b)
  1021. {
  1022. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1023. addNewBonus(b);
  1024. }
  1025. if (garrisonHero)
  1026. {
  1027. b->val = 0;
  1028. CBonusSystemNode::treeHasChanged();
  1029. }
  1030. else
  1031. CArmedInstance::updateMoraleBonusFromArmy();
  1032. }
  1033. void CGTownInstance::recreateBuildingsBonuses()
  1034. {
  1035. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  1036. BonusList bl;
  1037. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  1038. for(auto b : bl)
  1039. removeBonus(b);
  1040. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  1041. if(!addBonusIfBuilt(BuildingID::BROTHERHOOD, BuildingSubID::BROTHERHOOD_OF_SWORD, Bonus::MORALE, +2))
  1042. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  1043. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, BuildingSubID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  1044. addBonusIfBuilt(BuildingID::STORMCLOUDS, BuildingSubID::SPELL_POWER_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER);//works as Brimstone Clouds
  1045. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, BuildingSubID::ATTACK_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK);//works as Blood Obelisk
  1046. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, BuildingSubID::DEFENSE_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE);//works as Glyphs of Fear
  1047. if(subID == ETownType::CASTLE) //castle
  1048. {
  1049. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  1050. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  1051. }
  1052. else if(subID == ETownType::RAMPART) //rampart
  1053. {
  1054. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  1055. }
  1056. else if(subID == ETownType::TOWER) //tower
  1057. {
  1058. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  1059. }
  1060. else if(subID == ETownType::NECROPOLIS) //necropolis
  1061. {
  1062. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  1063. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  1064. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  1065. }
  1066. else if(subID == ETownType::DUNGEON) //Dungeon
  1067. {
  1068. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  1069. }
  1070. else if(subID == ETownType::STRONGHOLD) //Stronghold
  1071. {
  1072. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  1073. }
  1074. else if(subID == ETownType::FORTRESS) //Fortress
  1075. {
  1076. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  1077. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  1078. }
  1079. }
  1080. bool CGTownInstance::addBonusIfBuilt(BuildingID bid, BuildingSubID::EBuildingSubID subId, Bonus::BonusType type, int val, int subtype)
  1081. {
  1082. bool hasBuilt = false;
  1083. std::ostringstream descr;
  1084. for (const auto & bid : builtBuildings)
  1085. {
  1086. if (town->buildings.at(bid)->subId == subId)
  1087. {
  1088. descr << town->buildings.at(bid)->Name();
  1089. hasBuilt = true;
  1090. break;
  1091. }
  1092. }
  1093. if(hasBuilt)
  1094. hasBuilt = addBonusImpl(bid, type, val, emptyPropagator, descr.str(), subtype);
  1095. return hasBuilt;
  1096. }
  1097. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype)
  1098. {
  1099. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  1100. }
  1101. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype)
  1102. {
  1103. if(!hasBuilt(building))
  1104. return false;
  1105. std::ostringstream descr;
  1106. descr << town->buildings.at(building)->Name();
  1107. return addBonusImpl(building, type, val, prop, descr.str(), subtype);
  1108. }
  1109. bool CGTownInstance::addBonusImpl(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, const std::string & description, int subtype)
  1110. {
  1111. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, description, subtype);
  1112. if(prop)
  1113. b->addPropagator(prop);
  1114. addNewBonus(b);
  1115. return true;
  1116. }
  1117. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1118. {
  1119. //if (!(!!visitingHero == !h))
  1120. //{
  1121. // logGlobal->warn("Hero visiting town %s is %s ", name, (visitingHero.get() ? visitingHero->name : "NULL"));
  1122. // logGlobal->warn("New hero will be %s ", (h ? h->name : "NULL"));
  1123. //
  1124. //}
  1125. assert(!!visitingHero == !h);
  1126. if(h)
  1127. {
  1128. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  1129. assert(p);
  1130. h->detachFrom(p);
  1131. h->attachTo(&townAndVis);
  1132. visitingHero = h;
  1133. h->visitedTown = this;
  1134. h->inTownGarrison = false;
  1135. }
  1136. else
  1137. {
  1138. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  1139. visitingHero->visitedTown = nullptr;
  1140. visitingHero->detachFrom(&townAndVis);
  1141. visitingHero->attachTo(p);
  1142. visitingHero = nullptr;
  1143. }
  1144. }
  1145. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1146. {
  1147. assert(!!garrisonHero == !h);
  1148. if(h)
  1149. {
  1150. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  1151. assert(p);
  1152. h->detachFrom(p);
  1153. h->attachTo(this);
  1154. garrisonHero = h;
  1155. h->visitedTown = this;
  1156. h->inTownGarrison = true;
  1157. }
  1158. else
  1159. {
  1160. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  1161. garrisonHero->visitedTown = nullptr;
  1162. garrisonHero->inTownGarrison = false;
  1163. garrisonHero->detachFrom(this);
  1164. garrisonHero->attachTo(p);
  1165. garrisonHero = nullptr;
  1166. }
  1167. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1168. }
  1169. bool CGTownInstance::armedGarrison() const
  1170. {
  1171. return stacksCount() || garrisonHero;
  1172. }
  1173. const CTown * CGTownInstance::getTown() const
  1174. {
  1175. if(ID == Obj::RANDOM_TOWN)
  1176. return VLC->townh->randomTown;
  1177. else
  1178. {
  1179. if(nullptr == town)
  1180. {
  1181. return VLC->townh->factions[subID]->town;
  1182. }
  1183. else
  1184. return town;
  1185. }
  1186. }
  1187. int CGTownInstance::getTownLevel() const
  1188. {
  1189. // count all buildings that are not upgrades
  1190. int level = 0;
  1191. for (const auto & bid : builtBuildings)
  1192. {
  1193. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1194. level++;
  1195. }
  1196. return level;
  1197. }
  1198. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  1199. {
  1200. return &townAndVis;
  1201. }
  1202. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1203. {
  1204. if(garrisonHero)
  1205. return garrisonHero;
  1206. return this;
  1207. }
  1208. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1209. {
  1210. for(const auto building : bonusingBuildings)
  1211. {
  1212. if(building->getBuildingSubtype() == subId)
  1213. return building;
  1214. }
  1215. return nullptr;
  1216. }
  1217. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1218. {
  1219. for(const auto & bid : builtBuildings)
  1220. {
  1221. if(town->buildings.at(bid)->subId == buildingID)
  1222. return true;
  1223. }
  1224. return false;
  1225. }
  1226. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  1227. {
  1228. return vstd::contains(builtBuildings, buildingID);
  1229. }
  1230. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  1231. {
  1232. if (townID == town->faction->index || townID == ETownType::ANY)
  1233. return hasBuilt(buildingID);
  1234. return false;
  1235. }
  1236. TResources CGTownInstance::getBuildingCost(BuildingID buildingID) const
  1237. {
  1238. if (vstd::contains(town->buildings, buildingID))
  1239. return town->buildings.at(buildingID)->resources;
  1240. else
  1241. {
  1242. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1243. return TResources();
  1244. }
  1245. }
  1246. CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool deep) const
  1247. {
  1248. const CBuilding * building = town->buildings.at(buildID);
  1249. //TODO: find better solution to prevent infinite loops
  1250. std::set<BuildingID> processed;
  1251. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1252. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1253. {
  1254. const CBuilding * build = town->buildings.at(id);
  1255. CBuilding::TRequired::OperatorAll requirements;
  1256. if (!hasBuilt(id))
  1257. {
  1258. if (deep)
  1259. requirements.expressions.push_back(id);
  1260. else
  1261. return id;
  1262. }
  1263. if(!vstd::contains(processed, id))
  1264. {
  1265. processed.insert(id);
  1266. if (build->upgrade != BuildingID::NONE)
  1267. requirements.expressions.push_back(dependTest(build->upgrade));
  1268. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1269. }
  1270. return requirements;
  1271. };
  1272. CBuilding::TRequired::OperatorAll requirements;
  1273. if (building->upgrade != BuildingID::NONE)
  1274. {
  1275. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1276. requirements.expressions.push_back(dependTest(upgr->bid));
  1277. processed.clear();
  1278. }
  1279. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1280. CBuilding::TRequired::Variant variant(requirements);
  1281. CBuilding::TRequired ret(variant);
  1282. ret.minimize();
  1283. return ret;
  1284. }
  1285. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1286. {
  1287. if(visitingHero == h)
  1288. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1289. else if(garrisonHero == h)
  1290. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1291. else
  1292. {
  1293. //should never ever happen
  1294. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->name, structureInstanceID);
  1295. throw std::runtime_error("internal error");
  1296. }
  1297. }
  1298. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1299. {
  1300. if(result.winner == 0)
  1301. {
  1302. clearArmy();
  1303. removeCapitols(hero->getOwner());
  1304. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  1305. FoWChange fw;
  1306. fw.player = hero->tempOwner;
  1307. fw.mode = 1;
  1308. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), tempOwner, 1);
  1309. cb->sendAndApply (&fw);
  1310. }
  1311. }
  1312. void CGTownInstance::afterAddToMap(CMap * map)
  1313. {
  1314. if(ID == Obj::TOWN)
  1315. map->towns.push_back(this);
  1316. }
  1317. void CGTownInstance::reset()
  1318. {
  1319. CGTownInstance::merchantArtifacts.clear();
  1320. CGTownInstance::universitySkills.clear();
  1321. }
  1322. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1323. {
  1324. CGObjectInstance::serializeJsonOwner(handler);
  1325. CCreatureSet::serializeJson(handler, "army", 7);
  1326. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1327. handler.serializeString("name", name);
  1328. {
  1329. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1330. {
  1331. auto rawId = VLC->modh->identifiers.getIdentifier("core", getTown()->getBuildingScope(), identifier);
  1332. if(rawId)
  1333. return rawId.get();
  1334. else
  1335. return -1;
  1336. };
  1337. auto encodeBuilding = [this](si32 index) -> std::string
  1338. {
  1339. return getTown()->buildings.at(BuildingID(index))->identifier;
  1340. };
  1341. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1342. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1343. if(handler.saving)
  1344. {
  1345. bool customBuildings = false;
  1346. boost::logic::tribool hasFort(false);
  1347. for(const BuildingID id : forbiddenBuildings)
  1348. {
  1349. buildingsLIC.none.insert(id);
  1350. customBuildings = true;
  1351. }
  1352. for(const BuildingID id : builtBuildings)
  1353. {
  1354. if(id == BuildingID::DEFAULT)
  1355. continue;
  1356. const CBuilding * building = getTown()->buildings.at(id);
  1357. if(building->mode == CBuilding::BUILD_AUTO)
  1358. continue;
  1359. if(id == BuildingID::FORT)
  1360. hasFort = true;
  1361. buildingsLIC.all.insert(id);
  1362. customBuildings = true;
  1363. }
  1364. if(customBuildings)
  1365. handler.serializeLIC("buildings", buildingsLIC);
  1366. else
  1367. handler.serializeBool("hasFort",hasFort);
  1368. }
  1369. else
  1370. {
  1371. handler.serializeLIC("buildings", buildingsLIC);
  1372. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1373. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1374. {
  1375. builtBuildings.insert(BuildingID::DEFAULT);
  1376. bool hasFort = false;
  1377. handler.serializeBool("hasFort",hasFort);
  1378. if(hasFort)
  1379. builtBuildings.insert(BuildingID::FORT);
  1380. }
  1381. else
  1382. {
  1383. for(const si32 item : buildingsLIC.none)
  1384. forbiddenBuildings.insert(BuildingID(item));
  1385. for(const si32 item : buildingsLIC.all)
  1386. builtBuildings.insert(BuildingID(item));
  1387. }
  1388. }
  1389. }
  1390. {
  1391. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1392. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1393. if(handler.saving)
  1394. {
  1395. for(SpellID id : possibleSpells)
  1396. spellsLIC.any[id.num] = true;
  1397. for(SpellID id : obligatorySpells)
  1398. spellsLIC.all[id.num] = true;
  1399. }
  1400. handler.serializeLIC("spells", spellsLIC);
  1401. if(!handler.saving)
  1402. {
  1403. possibleSpells.clear();
  1404. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1405. {
  1406. if(spellsLIC.any[idx])
  1407. possibleSpells.push_back(SpellID(idx));
  1408. }
  1409. obligatorySpells.clear();
  1410. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1411. {
  1412. if(spellsLIC.all[idx])
  1413. obligatorySpells.push_back(SpellID(idx));
  1414. }
  1415. }
  1416. }
  1417. }
  1418. COPWBonus::COPWBonus (BuildingID bid, BuildingSubID::EBuildingSubID subId, CGTownInstance *TOWN)
  1419. {
  1420. bID = bid;
  1421. bType = subId;
  1422. town = TOWN;
  1423. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1424. }
  1425. void COPWBonus::setProperty(ui8 what, ui32 val)
  1426. {
  1427. switch (what)
  1428. {
  1429. case ObjProperty::VISITORS:
  1430. visitors.insert(val);
  1431. break;
  1432. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1433. visitors.clear();
  1434. break;
  1435. }
  1436. }
  1437. void COPWBonus::onHeroVisit(const CGHeroInstance * h) const
  1438. {
  1439. ObjectInstanceID heroID = h->id;
  1440. if (town->hasBuilt(bID))
  1441. {
  1442. InfoWindow iw;
  1443. iw.player = h->tempOwner;
  1444. switch (this->bType)
  1445. {
  1446. case BuildingSubID::STABLES:
  1447. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1448. {
  1449. GiveBonus gb;
  1450. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  1451. gb.id = heroID.getNum();
  1452. cb->giveHeroBonus(&gb);
  1453. SetMovePoints mp;
  1454. mp.val = 600;
  1455. mp.absolute = false;
  1456. mp.hid = heroID;
  1457. cb->setMovePoints(&mp);
  1458. iw.text << VLC->generaltexth->allTexts[580];
  1459. cb->showInfoDialog(&iw);
  1460. }
  1461. break;
  1462. case BuildingSubID::MANA_VORTEX:
  1463. if (visitors.empty())
  1464. {
  1465. if (h->mana < h->manaLimit() * 2)
  1466. cb->setManaPoints(heroID, 2 * h->manaLimit());
  1467. //TODO: investigate line below
  1468. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1469. iw.text << VLC->generaltexth->allTexts[579];
  1470. cb->showInfoDialog(&iw);
  1471. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1472. town->addHeroToStructureVisitors(h, indexOnTV);
  1473. }
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  1479. {
  1480. bID = index;
  1481. town = TOWN;
  1482. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1483. }
  1484. void CTownBonus::setProperty (ui8 what, ui32 val)
  1485. {
  1486. if(what == ObjProperty::VISITORS)
  1487. visitors.insert(ObjectInstanceID(val));
  1488. }
  1489. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1490. {
  1491. ObjectInstanceID heroID = h->id;
  1492. if (town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1493. {
  1494. si32 mid=0;
  1495. si64 val = 0;
  1496. InfoWindow iw;
  1497. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  1498. switch (bID)
  1499. {
  1500. case BuildingID::SPECIAL_4:
  1501. switch(town->subID)
  1502. {
  1503. case ETownType::TOWER: //wall
  1504. what = PrimarySkill::KNOWLEDGE;
  1505. val = 1;
  1506. mid = 581;
  1507. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  1508. break;
  1509. case ETownType::INFERNO: //order of fire
  1510. what = PrimarySkill::SPELL_POWER;
  1511. val = 1;
  1512. mid = 582;
  1513. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  1514. break;
  1515. case ETownType::STRONGHOLD://hall of Valhalla
  1516. what = PrimarySkill::ATTACK;
  1517. val = 1;
  1518. mid = 584;
  1519. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  1520. break;
  1521. case ETownType::DUNGEON://academy of battle scholars
  1522. what = PrimarySkill::EXPERIENCE;
  1523. val = static_cast<int>(h->calculateXp(1000));
  1524. mid = 583;
  1525. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  1526. break;
  1527. }
  1528. break;
  1529. case BuildingID::SPECIAL_1:
  1530. switch(town->subID)
  1531. {
  1532. case ETownType::FORTRESS: //cage of warlords
  1533. what = PrimarySkill::DEFENSE;
  1534. val = 1;
  1535. mid = 585;
  1536. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  1537. break;
  1538. }
  1539. break;
  1540. }
  1541. assert(mid);
  1542. iw.player = cb->getOwner(heroID);
  1543. iw.text << VLC->generaltexth->allTexts[mid];
  1544. cb->showInfoDialog(&iw);
  1545. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1546. town->addHeroToStructureVisitors(h, indexOnTV);
  1547. }
  1548. }
  1549. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1550. : count(_count)
  1551. {
  1552. description = boost::str(boost::format(format) % count);
  1553. }
  1554. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  1555. : count(_count)
  1556. {
  1557. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  1558. }
  1559. GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
  1560. : count(_count)
  1561. {
  1562. description = fullDescription;
  1563. }
  1564. CTownAndVisitingHero::CTownAndVisitingHero()
  1565. {
  1566. setNodeType(TOWN_AND_VISITOR);
  1567. }
  1568. int GrowthInfo::totalGrowth() const
  1569. {
  1570. int ret = 0;
  1571. for(const Entry &entry : entries)
  1572. ret += entry.count;
  1573. return ret;
  1574. }