CGTownInstance.cpp 49 KB

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