CGTownInstance.cpp 50 KB

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