CGTownInstance.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  644. {
  645. return town->getBuildingType(subId) != BuildingID::NONE;
  646. }
  647. //it does not check hasBuilt because this check is in the OnHeroVisit handler
  648. void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
  649. {
  650. auto bid = town->getBuildingType(subID);
  651. if(bid != BuildingID::NONE)
  652. bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
  653. }
  654. void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
  655. {
  656. auto bid = town->getBuildingType(subID);
  657. if(bid != BuildingID::NONE)
  658. bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
  659. }
  660. void CGTownInstance::addTownBonuses()
  661. {
  662. for(const auto & kvp : town->buildings)
  663. {
  664. if(kvp.second->IsVisitingBonus())
  665. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  666. if(kvp.second->IsWeekBonus())
  667. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  668. }
  669. }
  670. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  671. {
  672. blockVisit = true;
  673. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  674. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  675. else
  676. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  677. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  678. {
  679. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  680. int upgradeNum = 0;
  681. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  682. {
  683. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  684. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  685. }
  686. }
  687. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  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) //no garrison bonuses here, only week and visiting bonuses
  697. {
  698. switch (this->town->faction->index)
  699. {
  700. case ETownType::CASTLE:
  701. building->setBuildingSubtype(BuildingSubID::STABLES);
  702. break;
  703. case ETownType::DUNGEON:
  704. if(building->getBuildingType() == BuildingID::SPECIAL_2)
  705. building->setBuildingSubtype(BuildingSubID::MANA_VORTEX);
  706. else if(building->getBuildingType() == BuildingID::SPECIAL_4)
  707. building->setBuildingSubtype(BuildingSubID::EXPERIENCE_VISITING_BONUS);
  708. break;
  709. case ETownType::TOWER:
  710. building->setBuildingSubtype(BuildingSubID::KNOWLEDGE_VISITING_BONUS);
  711. break;
  712. case ETownType::STRONGHOLD:
  713. building->setBuildingSubtype(BuildingSubID::ATTACK_VISITING_BONUS);
  714. break;
  715. case ETownType::INFERNO:
  716. building->setBuildingSubtype(BuildingSubID::SPELL_POWER_VISITING_BONUS);
  717. break;
  718. case ETownType::FORTRESS:
  719. building->setBuildingSubtype(BuildingSubID::DEFENSE_VISITING_BONUS);
  720. break;
  721. }
  722. }
  723. }
  724. //secondly, supplement bonusing buildings list and active bonuses; subtypes for these objects are already set in update792
  725. for (auto & kvp : town->buildings)
  726. {
  727. auto & building = kvp.second;
  728. if(building->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  729. {
  730. if(!hasBuiltInOldWay(ETownType::DUNGEON, BuildingID::PORTAL_OF_SUMMON))
  731. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  732. continue;
  733. }
  734. if(!building->IsVisitingBonus() && !building->IsWeekBonus()) //it's not bonusing => nothing to handle
  735. continue;
  736. if(getBonusingBuilding(building->subId) != nullptr) //it's already added => already handled
  737. continue;
  738. ///'hasBuilt' checking for bonuses is in the onHeroVisit handler
  739. if(building->IsWeekBonus())
  740. tryAddOnePerWeekBonus(building->subId);
  741. if(building->IsVisitingBonus())
  742. tryAddVisitingBonus(building->subId);
  743. }
  744. recreateBuildingsBonuses(); ///Clear all bonuses and recreate
  745. }
  746. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, BuildingID bid) const
  747. {
  748. return (this->town->faction != nullptr && this->town->faction->index == type && hasBuilt(bid));
  749. }
  750. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  751. {
  752. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  753. {
  754. //give resources if there's a Mystic Pond
  755. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  756. && cb->getDate(Date::DAY) != 1
  757. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  758. )
  759. {
  760. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  761. resID = (resID==2)?1:resID;
  762. int resVal = rand.nextInt(1, 4);//with size 1..4
  763. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  764. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  765. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  766. }
  767. auto manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  768. if (manaVortex != nullptr)
  769. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  770. //get Mana Vortex or Stables bonuses
  771. //same code is in the CGameHandler::buildStructure method
  772. if (visitingHero != nullptr)
  773. cb->visitCastleObjects(this, visitingHero);
  774. if (garrisonHero != nullptr)
  775. cb->visitCastleObjects(this, garrisonHero);
  776. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  777. {
  778. std::vector<SlotID> nativeCrits; //slots
  779. for (auto & elem : Slots())
  780. {
  781. if (elem.second->type->faction == subID) //native
  782. {
  783. nativeCrits.push_back(elem.first); //collect matching slots
  784. }
  785. }
  786. if (nativeCrits.size())
  787. {
  788. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  789. StackLocation sl(this, pos);
  790. const CCreature *c = getCreature(pos);
  791. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  792. {
  793. cb->changeStackCount(sl, c->growth);
  794. }
  795. else //upgrade
  796. {
  797. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  798. }
  799. }
  800. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  801. {
  802. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  803. if (!town->creatures[i].empty())
  804. {
  805. CreatureID c = town->creatures[i][0];
  806. SlotID n;
  807. TQuantity count = creatureGrowth(i);
  808. if (!count) // no dwelling
  809. count = VLC->creh->creatures[c]->growth;
  810. {//no lower tiers or above current month
  811. if ((n = getSlotFor(c)).validSlot())
  812. {
  813. StackLocation sl(this, n);
  814. if (slotEmpty(n))
  815. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  816. else //add to existing
  817. cb->changeStackCount(sl, count);
  818. }
  819. }
  820. }
  821. }
  822. }
  823. }
  824. }
  825. /*
  826. int3 CGTownInstance::getSightCenter() const
  827. {
  828. return pos - int3(2,0,0);
  829. }
  830. */
  831. bool CGTownInstance::passableFor(PlayerColor color) const
  832. {
  833. if (!armedGarrison())//empty castle - anyone can visit
  834. return true;
  835. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  836. return false;
  837. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  838. }
  839. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  840. {
  841. offsets = {int3(-1,2,0), int3(-3,2,0)};
  842. }
  843. void CGTownInstance::mergeGarrisonOnSiege() const
  844. {
  845. auto getWeakestStackSlot = [&](ui64 powerLimit)
  846. {
  847. std::vector<SlotID> weakSlots;
  848. auto stacksList = visitingHero->stacks;
  849. std::pair<SlotID, CStackInstance *> pair;
  850. while(stacksList.size())
  851. {
  852. pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
  853. {
  854. return elem.second->getPower();
  855. });
  856. if(powerLimit > pair.second->getPower() &&
  857. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  858. {
  859. weakSlots.push_back(pair.first);
  860. stacksList.erase(pair.first);
  861. }
  862. else
  863. break;
  864. }
  865. if(weakSlots.size())
  866. return *std::max_element(weakSlots.begin(), weakSlots.end());
  867. return SlotID();
  868. };
  869. auto count = static_cast<int>(stacks.size());
  870. for(int i = 0; i < count; i++)
  871. {
  872. auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
  873. {
  874. ui64 power = elem.second->getPower();
  875. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  876. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  877. power += visitingHero->getStack(dst).getPower();
  878. return power;
  879. });
  880. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  881. if(dst.validSlot())
  882. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  883. else
  884. {
  885. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  886. if(dst.validSlot())
  887. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  888. }
  889. }
  890. }
  891. void CGTownInstance::removeCapitols (PlayerColor owner) const
  892. {
  893. if (hasCapitol()) // search if there's an older capitol
  894. {
  895. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  896. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  897. {
  898. if (*i != this && (*i)->hasCapitol())
  899. {
  900. RazeStructures rs;
  901. rs.tid = id;
  902. rs.bid.insert(BuildingID::CAPITOL);
  903. rs.destroyed = destroyed;
  904. cb->sendAndApply(&rs);
  905. return;
  906. }
  907. }
  908. }
  909. }
  910. void CGTownInstance::clearArmy() const
  911. {
  912. while(!stacks.empty())
  913. {
  914. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  915. }
  916. }
  917. int CGTownInstance::getBoatType() const
  918. {
  919. switch (town->faction->alignment)
  920. {
  921. case EAlignment::EVIL : return 0;
  922. case EAlignment::GOOD : return 1;
  923. case EAlignment::NEUTRAL : return 2;
  924. }
  925. assert(0);
  926. return -1;
  927. }
  928. int CGTownInstance::getMarketEfficiency() const
  929. {
  930. if(!hasBuiltSomeTradeBuilding())
  931. return 0;
  932. const PlayerState *p = cb->getPlayer(tempOwner);
  933. assert(p);
  934. int marketCount = 0;
  935. for(const CGTownInstance *t : p->towns)
  936. if(t->hasBuiltSomeTradeBuilding())
  937. marketCount++;
  938. return marketCount;
  939. }
  940. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  941. {
  942. switch(mode)
  943. {
  944. case EMarketMode::RESOURCE_RESOURCE:
  945. case EMarketMode::RESOURCE_PLAYER:
  946. return hasBuilt(BuildingID::MARKETPLACE);
  947. case EMarketMode::ARTIFACT_RESOURCE:
  948. case EMarketMode::RESOURCE_ARTIFACT:
  949. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  950. case EMarketMode::CREATURE_RESOURCE:
  951. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  952. case EMarketMode::CREATURE_UNDEAD:
  953. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  954. case EMarketMode::RESOURCE_SKILL:
  955. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  956. default:
  957. assert(0);
  958. return false;
  959. }
  960. }
  961. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  962. {
  963. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  964. {
  965. std::vector<int> ret;
  966. for(const CArtifact *a : merchantArtifacts)
  967. if(a)
  968. ret.push_back(a->id);
  969. else
  970. ret.push_back(-1);
  971. return ret;
  972. }
  973. else if ( mode == EMarketMode::RESOURCE_SKILL )
  974. {
  975. return universitySkills;
  976. }
  977. else
  978. return IMarket::availableItemsIds(mode);
  979. }
  980. void CGTownInstance::setType(si32 ID, si32 subID)
  981. {
  982. assert(ID == Obj::TOWN); // just in case
  983. CGObjectInstance::setType(ID, subID);
  984. town = VLC->townh->factions[subID]->town;
  985. randomizeArmy(subID);
  986. updateAppearance();
  987. }
  988. void CGTownInstance::updateAppearance()
  989. {
  990. //FIXME: not the best way to do this
  991. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
  992. if (app)
  993. appearance = app.get();
  994. }
  995. std::string CGTownInstance::nodeName() const
  996. {
  997. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  998. }
  999. void CGTownInstance::deserializationFix()
  1000. {
  1001. attachTo(&townAndVis);
  1002. //Hero is already handled by CGameState::attachArmedObjects
  1003. // if(visitingHero)
  1004. // visitingHero->attachTo(&townAndVis);
  1005. // if(garrisonHero)
  1006. // garrisonHero->attachTo(this);
  1007. }
  1008. void CGTownInstance::updateMoraleBonusFromArmy()
  1009. {
  1010. auto b = getExportedBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  1011. if(!b)
  1012. {
  1013. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1014. addNewBonus(b);
  1015. }
  1016. if (garrisonHero)
  1017. {
  1018. b->val = 0;
  1019. CBonusSystemNode::treeHasChanged();
  1020. }
  1021. else
  1022. CArmedInstance::updateMoraleBonusFromArmy();
  1023. }
  1024. void CGTownInstance::recreateBuildingsBonuses()
  1025. {
  1026. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  1027. BonusList bl;
  1028. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  1029. for(auto b : bl)
  1030. removeBonus(b);
  1031. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  1032. if(!addBonusIfBuilt(BuildingSubID::BROTHERHOOD_OF_SWORD, Bonus::MORALE, +2))
  1033. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  1034. addBonusIfBuilt(BuildingSubID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  1035. addBonusIfBuilt(BuildingSubID::SPELL_POWER_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER);//works as Brimstone Clouds
  1036. addBonusIfBuilt(BuildingSubID::ATTACK_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK);//works as Blood Obelisk
  1037. addBonusIfBuilt(BuildingSubID::DEFENSE_GARRISON_BONUS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE);//works as Glyphs of Fear
  1038. addBonusIfBuilt(BuildingSubID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  1039. if(subID == ETownType::CASTLE) //castle
  1040. {
  1041. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  1042. }
  1043. else if(subID == ETownType::RAMPART) //rampart
  1044. {
  1045. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  1046. }
  1047. else if(subID == ETownType::TOWER) //tower
  1048. {
  1049. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  1050. }
  1051. else if(subID == ETownType::NECROPOLIS) //necropolis
  1052. {
  1053. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  1054. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  1055. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  1056. }
  1057. else if(subID == ETownType::DUNGEON) //Dungeon
  1058. {
  1059. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  1060. }
  1061. else if(subID == ETownType::STRONGHOLD) //Stronghold
  1062. {
  1063. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  1064. }
  1065. else if(subID == ETownType::FORTRESS) //Fortress
  1066. {
  1067. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  1068. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  1069. }
  1070. }
  1071. bool CGTownInstance::addBonusIfBuilt(BuildingSubID::EBuildingSubID subId, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype)
  1072. {
  1073. BuildingID currentBid = BuildingID::NONE;
  1074. std::ostringstream descr;
  1075. for(const auto & bid : builtBuildings)
  1076. {
  1077. if(town->buildings.at(bid)->subId == subId)
  1078. {
  1079. descr << town->buildings.at(bid)->Name();
  1080. currentBid = bid;
  1081. break;
  1082. }
  1083. }
  1084. return currentBid == BuildingID::NONE ? false
  1085. : addBonusImpl(currentBid, type, val, prop, descr.str(), subtype);
  1086. }
  1087. bool CGTownInstance::addBonusIfBuilt(BuildingSubID::EBuildingSubID subId, Bonus::BonusType type, int val, int subtype)
  1088. {
  1089. return addBonusIfBuilt(subId, type, val, emptyPropagator, subtype);
  1090. }
  1091. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype)
  1092. {
  1093. if(!hasBuilt(building))
  1094. return false;
  1095. std::ostringstream descr;
  1096. descr << town->buildings.at(building)->Name();
  1097. return addBonusImpl(building, type, val, prop, descr.str(), subtype);
  1098. }
  1099. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype)
  1100. {
  1101. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  1102. }
  1103. bool CGTownInstance::addBonusImpl(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, const std::string & description, int subtype)
  1104. {
  1105. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, description, subtype);
  1106. if(prop)
  1107. b->addPropagator(prop);
  1108. addNewBonus(b);
  1109. return true;
  1110. }
  1111. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1112. {
  1113. //if (!(!!visitingHero == !h))
  1114. //{
  1115. // logGlobal->warn("Hero visiting town %s is %s ", name, (visitingHero.get() ? visitingHero->name : "NULL"));
  1116. // logGlobal->warn("New hero will be %s ", (h ? h->name : "NULL"));
  1117. //
  1118. //}
  1119. assert(!!visitingHero == !h);
  1120. if(h)
  1121. {
  1122. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  1123. assert(p);
  1124. h->detachFrom(p);
  1125. h->attachTo(&townAndVis);
  1126. visitingHero = h;
  1127. h->visitedTown = this;
  1128. h->inTownGarrison = false;
  1129. }
  1130. else
  1131. {
  1132. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  1133. visitingHero->visitedTown = nullptr;
  1134. visitingHero->detachFrom(&townAndVis);
  1135. visitingHero->attachTo(p);
  1136. visitingHero = nullptr;
  1137. }
  1138. }
  1139. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1140. {
  1141. assert(!!garrisonHero == !h);
  1142. if(h)
  1143. {
  1144. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  1145. assert(p);
  1146. h->detachFrom(p);
  1147. h->attachTo(this);
  1148. garrisonHero = h;
  1149. h->visitedTown = this;
  1150. h->inTownGarrison = true;
  1151. }
  1152. else
  1153. {
  1154. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  1155. garrisonHero->visitedTown = nullptr;
  1156. garrisonHero->inTownGarrison = false;
  1157. garrisonHero->detachFrom(this);
  1158. garrisonHero->attachTo(p);
  1159. garrisonHero = nullptr;
  1160. }
  1161. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1162. }
  1163. bool CGTownInstance::armedGarrison() const
  1164. {
  1165. return stacksCount() || garrisonHero;
  1166. }
  1167. const CTown * CGTownInstance::getTown() const
  1168. {
  1169. if(ID == Obj::RANDOM_TOWN)
  1170. return VLC->townh->randomTown;
  1171. else
  1172. {
  1173. if(nullptr == town)
  1174. {
  1175. return VLC->townh->factions[subID]->town;
  1176. }
  1177. else
  1178. return town;
  1179. }
  1180. }
  1181. int CGTownInstance::getTownLevel() const
  1182. {
  1183. // count all buildings that are not upgrades
  1184. int level = 0;
  1185. for (const auto & bid : builtBuildings)
  1186. {
  1187. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1188. level++;
  1189. }
  1190. return level;
  1191. }
  1192. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  1193. {
  1194. return &townAndVis;
  1195. }
  1196. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1197. {
  1198. if(garrisonHero)
  1199. return garrisonHero;
  1200. return this;
  1201. }
  1202. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1203. {
  1204. for(const auto building : bonusingBuildings)
  1205. {
  1206. if(building->getBuildingSubtype() == subId)
  1207. return building;
  1208. }
  1209. return nullptr;
  1210. }
  1211. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  1212. {
  1213. for (const auto & bid : builtBuildings)
  1214. {
  1215. if(town->buildings.at(bid)->IsTradeBuilding())
  1216. return true;
  1217. }
  1218. return false;
  1219. }
  1220. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1221. {
  1222. for(const auto & bid : builtBuildings)
  1223. {
  1224. if(town->buildings.at(bid)->subId == buildingID)
  1225. return true;
  1226. }
  1227. return false;
  1228. }
  1229. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  1230. {
  1231. return vstd::contains(builtBuildings, buildingID);
  1232. }
  1233. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  1234. {
  1235. if (townID == town->faction->index || townID == ETownType::ANY)
  1236. return hasBuilt(buildingID);
  1237. return false;
  1238. }
  1239. TResources CGTownInstance::getBuildingCost(BuildingID buildingID) const
  1240. {
  1241. if (vstd::contains(town->buildings, buildingID))
  1242. return town->buildings.at(buildingID)->resources;
  1243. else
  1244. {
  1245. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1246. return TResources();
  1247. }
  1248. }
  1249. CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool deep) const
  1250. {
  1251. const CBuilding * building = town->buildings.at(buildID);
  1252. //TODO: find better solution to prevent infinite loops
  1253. std::set<BuildingID> processed;
  1254. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1255. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1256. {
  1257. const CBuilding * build = town->buildings.at(id);
  1258. CBuilding::TRequired::OperatorAll requirements;
  1259. if (!hasBuilt(id))
  1260. {
  1261. if (deep)
  1262. requirements.expressions.push_back(id);
  1263. else
  1264. return id;
  1265. }
  1266. if(!vstd::contains(processed, id))
  1267. {
  1268. processed.insert(id);
  1269. if (build->upgrade != BuildingID::NONE)
  1270. requirements.expressions.push_back(dependTest(build->upgrade));
  1271. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1272. }
  1273. return requirements;
  1274. };
  1275. CBuilding::TRequired::OperatorAll requirements;
  1276. if (building->upgrade != BuildingID::NONE)
  1277. {
  1278. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1279. requirements.expressions.push_back(dependTest(upgr->bid));
  1280. processed.clear();
  1281. }
  1282. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1283. CBuilding::TRequired::Variant variant(requirements);
  1284. CBuilding::TRequired ret(variant);
  1285. ret.minimize();
  1286. return ret;
  1287. }
  1288. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1289. {
  1290. if(visitingHero == h)
  1291. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1292. else if(garrisonHero == h)
  1293. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1294. else
  1295. {
  1296. //should never ever happen
  1297. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->name, structureInstanceID);
  1298. throw std::runtime_error("internal error");
  1299. }
  1300. }
  1301. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1302. {
  1303. if(result.winner == 0)
  1304. {
  1305. clearArmy();
  1306. removeCapitols(hero->getOwner());
  1307. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  1308. FoWChange fw;
  1309. fw.player = hero->tempOwner;
  1310. fw.mode = 1;
  1311. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), tempOwner, 1);
  1312. cb->sendAndApply (&fw);
  1313. }
  1314. }
  1315. void CGTownInstance::afterAddToMap(CMap * map)
  1316. {
  1317. if(ID == Obj::TOWN)
  1318. map->towns.push_back(this);
  1319. }
  1320. void CGTownInstance::reset()
  1321. {
  1322. CGTownInstance::merchantArtifacts.clear();
  1323. CGTownInstance::universitySkills.clear();
  1324. }
  1325. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1326. {
  1327. CGObjectInstance::serializeJsonOwner(handler);
  1328. CCreatureSet::serializeJson(handler, "army", 7);
  1329. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1330. handler.serializeString("name", name);
  1331. {
  1332. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1333. {
  1334. auto rawId = VLC->modh->identifiers.getIdentifier("core", getTown()->getBuildingScope(), identifier);
  1335. if(rawId)
  1336. return rawId.get();
  1337. else
  1338. return -1;
  1339. };
  1340. auto encodeBuilding = [this](si32 index) -> std::string
  1341. {
  1342. return getTown()->buildings.at(BuildingID(index))->identifier;
  1343. };
  1344. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1345. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1346. if(handler.saving)
  1347. {
  1348. bool customBuildings = false;
  1349. boost::logic::tribool hasFort(false);
  1350. for(const BuildingID id : forbiddenBuildings)
  1351. {
  1352. buildingsLIC.none.insert(id);
  1353. customBuildings = true;
  1354. }
  1355. for(const BuildingID id : builtBuildings)
  1356. {
  1357. if(id == BuildingID::DEFAULT)
  1358. continue;
  1359. const CBuilding * building = getTown()->buildings.at(id);
  1360. if(building->mode == CBuilding::BUILD_AUTO)
  1361. continue;
  1362. if(id == BuildingID::FORT)
  1363. hasFort = true;
  1364. buildingsLIC.all.insert(id);
  1365. customBuildings = true;
  1366. }
  1367. if(customBuildings)
  1368. handler.serializeLIC("buildings", buildingsLIC);
  1369. else
  1370. handler.serializeBool("hasFort",hasFort);
  1371. }
  1372. else
  1373. {
  1374. handler.serializeLIC("buildings", buildingsLIC);
  1375. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1376. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1377. {
  1378. builtBuildings.insert(BuildingID::DEFAULT);
  1379. bool hasFort = false;
  1380. handler.serializeBool("hasFort",hasFort);
  1381. if(hasFort)
  1382. builtBuildings.insert(BuildingID::FORT);
  1383. }
  1384. else
  1385. {
  1386. for(const si32 item : buildingsLIC.none)
  1387. forbiddenBuildings.insert(BuildingID(item));
  1388. for(const si32 item : buildingsLIC.all)
  1389. builtBuildings.insert(BuildingID(item));
  1390. }
  1391. }
  1392. }
  1393. {
  1394. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1395. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1396. if(handler.saving)
  1397. {
  1398. for(SpellID id : possibleSpells)
  1399. spellsLIC.any[id.num] = true;
  1400. for(SpellID id : obligatorySpells)
  1401. spellsLIC.all[id.num] = true;
  1402. }
  1403. handler.serializeLIC("spells", spellsLIC);
  1404. if(!handler.saving)
  1405. {
  1406. possibleSpells.clear();
  1407. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1408. {
  1409. if(spellsLIC.any[idx])
  1410. possibleSpells.push_back(SpellID(idx));
  1411. }
  1412. obligatorySpells.clear();
  1413. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1414. {
  1415. if(spellsLIC.all[idx])
  1416. obligatorySpells.push_back(SpellID(idx));
  1417. }
  1418. }
  1419. }
  1420. }
  1421. COPWBonus::COPWBonus (BuildingID bid, BuildingSubID::EBuildingSubID subId, CGTownInstance *TOWN)
  1422. {
  1423. bID = bid;
  1424. bType = subId;
  1425. town = TOWN;
  1426. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1427. }
  1428. void COPWBonus::setProperty(ui8 what, ui32 val)
  1429. {
  1430. switch (what)
  1431. {
  1432. case ObjProperty::VISITORS:
  1433. visitors.insert(val);
  1434. break;
  1435. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1436. visitors.clear();
  1437. break;
  1438. }
  1439. }
  1440. void COPWBonus::onHeroVisit(const CGHeroInstance * h) const
  1441. {
  1442. ObjectInstanceID heroID = h->id;
  1443. if (town->hasBuilt(bID))
  1444. {
  1445. InfoWindow iw;
  1446. iw.player = h->tempOwner;
  1447. switch (this->bType)
  1448. {
  1449. case BuildingSubID::STABLES:
  1450. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1451. {
  1452. GiveBonus gb;
  1453. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  1454. gb.id = heroID.getNum();
  1455. cb->giveHeroBonus(&gb);
  1456. SetMovePoints mp;
  1457. mp.val = 600;
  1458. mp.absolute = false;
  1459. mp.hid = heroID;
  1460. cb->setMovePoints(&mp);
  1461. iw.text << VLC->generaltexth->allTexts[580];
  1462. cb->showInfoDialog(&iw);
  1463. }
  1464. break;
  1465. case BuildingSubID::MANA_VORTEX:
  1466. if (visitors.empty())
  1467. {
  1468. if (h->mana < h->manaLimit() * 2)
  1469. cb->setManaPoints(heroID, 2 * h->manaLimit());
  1470. //TODO: investigate line below
  1471. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1472. iw.text << VLC->generaltexth->allTexts[579];
  1473. cb->showInfoDialog(&iw);
  1474. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1475. town->addHeroToStructureVisitors(h, indexOnTV);
  1476. }
  1477. break;
  1478. }
  1479. }
  1480. }
  1481. CTownBonus::CTownBonus (BuildingID index, BuildingSubID::EBuildingSubID subId, CGTownInstance *TOWN)
  1482. {
  1483. bID = index;
  1484. bType = subId;
  1485. town = TOWN;
  1486. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1487. }
  1488. void CTownBonus::setProperty (ui8 what, ui32 val)
  1489. {
  1490. if(what == ObjProperty::VISITORS)
  1491. visitors.insert(ObjectInstanceID(val));
  1492. }
  1493. void CTownBonus::onHeroVisit(const CGHeroInstance * h) const
  1494. {
  1495. ObjectInstanceID heroID = h->id;
  1496. if (town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1497. {
  1498. si32 mid = 0;
  1499. si64 val = 0;
  1500. InfoWindow iw;
  1501. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  1502. switch (bType)
  1503. {
  1504. case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
  1505. what = PrimarySkill::KNOWLEDGE;
  1506. val = 1;
  1507. mid = 581;
  1508. iw.components.push_back(Component(Component::PRIM_SKILL, 3, 1, 0));
  1509. break;
  1510. case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
  1511. what = PrimarySkill::SPELL_POWER;
  1512. val = 1;
  1513. mid = 582;
  1514. iw.components.push_back(Component(Component::PRIM_SKILL, 2, 1, 0));
  1515. break;
  1516. case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
  1517. what = PrimarySkill::ATTACK;
  1518. val = 1;
  1519. mid = 584;
  1520. iw.components.push_back(Component(Component::PRIM_SKILL, 0, 1, 0));
  1521. break;
  1522. case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
  1523. what = PrimarySkill::EXPERIENCE;
  1524. val = static_cast<int>(h->calculateXp(1000));
  1525. mid = 583;
  1526. iw.components.push_back(Component(Component::EXPERIENCE, 0, val, 0));
  1527. break;
  1528. case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
  1529. what = PrimarySkill::DEFENSE;
  1530. val = 1;
  1531. mid = 585;
  1532. iw.components.push_back(Component(Component::PRIM_SKILL, 1, 1, 0));
  1533. break;
  1534. }
  1535. assert(mid);
  1536. iw.player = cb->getOwner(heroID);
  1537. iw.text << VLC->generaltexth->allTexts[mid];
  1538. cb->showInfoDialog(&iw);
  1539. cb->changePrimSkill(cb->getHero(heroID), what, val);
  1540. town->addHeroToStructureVisitors(h, indexOnTV);
  1541. }
  1542. }
  1543. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1544. : count(_count)
  1545. {
  1546. description = boost::str(boost::format(format) % count);
  1547. }
  1548. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  1549. : count(_count)
  1550. {
  1551. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  1552. }
  1553. GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
  1554. : count(_count)
  1555. {
  1556. description = fullDescription;
  1557. }
  1558. CTownAndVisitingHero::CTownAndVisitingHero()
  1559. {
  1560. setNodeType(TOWN_AND_VISITOR);
  1561. }
  1562. int GrowthInfo::totalGrowth() const
  1563. {
  1564. int ret = 0;
  1565. for(const Entry &entry : entries)
  1566. ret += entry.count;
  1567. return ret;
  1568. }