CGTownInstance.cpp 50 KB

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