CGTownInstance.cpp 51 KB

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