CGTownInstance.cpp 51 KB

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