CGTownInstance.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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. //statue-of-legion-like bonus: % to base+castle
  486. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
  487. for(const auto & b : *bonuses2)
  488. {
  489. const auto growth = b->val * (base + castleBonus) / 100;
  490. ret.entries.push_back(GrowthInfo::Entry(growth, b->Description(growth)));
  491. }
  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. int dwellingBonus = 0;
  497. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  498. {
  499. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  500. }
  501. if(dwellingBonus)
  502. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  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->getNameTranslated(), 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->getNameTranslated(), name);
  642. }
  643. else
  644. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), name);
  645. }
  646. std::string CGTownInstance::getObjectName() const
  647. {
  648. return name + ", " + town->faction->getNameTranslated();
  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. TDmgRange CGTownInstance::getTowerDamageRange() const
  697. {
  698. assert(hasBuilt(BuildingID::CASTLE));
  699. // http://heroes.thelazy.net/wiki/Arrow_tower
  700. // base damage, irregardless of town level
  701. static const int baseDamage = 6;
  702. // extra damage, for each building in town
  703. static const int extraDamage = 1;
  704. const int minDamage = baseDamage + extraDamage * getTownLevel();
  705. return {
  706. minDamage,
  707. minDamage * 2
  708. };
  709. }
  710. TDmgRange CGTownInstance::getKeepDamageRange() const
  711. {
  712. assert(hasBuilt(BuildingID::CITADEL));
  713. // http://heroes.thelazy.net/wiki/Arrow_tower
  714. // base damage, irregardless of town level
  715. static const int baseDamage = 10;
  716. // extra damage, for each building in town
  717. static const int extraDamage = 2;
  718. const int minDamage = baseDamage + extraDamage * getTownLevel();
  719. return {
  720. minDamage,
  721. minDamage * 2
  722. };
  723. }
  724. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  725. {
  726. size_t i = 0;
  727. CGTownBuilding * freeIt = nullptr;
  728. for(i = 0; i != bonusingBuildings.size(); i++)
  729. {
  730. if(bonusingBuildings[i]->getBuildingType() == bid)
  731. {
  732. freeIt = bonusingBuildings[i];
  733. break;
  734. }
  735. }
  736. if(freeIt == nullptr)
  737. return;
  738. auto building = town->buildings.at(bid);
  739. auto isVisitingBonus = building->IsVisitingBonus();
  740. auto isWeekBonus = building->IsWeekBonus();
  741. if(!isVisitingBonus && !isWeekBonus)
  742. return;
  743. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  744. if(isVisitingBonus)
  745. delete (CTownBonus *)freeIt;
  746. else if(isWeekBonus)
  747. delete (COPWBonus *)freeIt;
  748. }
  749. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  750. {
  751. blockVisit = true;
  752. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  753. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  754. else
  755. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  756. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  757. {
  758. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  759. int upgradeNum = 0;
  760. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  761. {
  762. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  763. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  764. }
  765. }
  766. initOverriddenBids();
  767. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  768. recreateBuildingsBonuses();
  769. updateAppearance();
  770. }
  771. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, BuildingID bid) const
  772. {
  773. return (this->town->faction != nullptr && this->town->faction->getIndex() == type && hasBuilt(bid));
  774. }
  775. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  776. {
  777. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  778. {
  779. //give resources if there's a Mystic Pond
  780. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  781. && cb->getDate(Date::DAY) != 1
  782. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  783. )
  784. {
  785. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  786. resID = (resID==2)?1:resID;
  787. int resVal = rand.nextInt(1, 4);//with size 1..4
  788. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  789. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  790. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  791. }
  792. auto manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  793. if (manaVortex != nullptr)
  794. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  795. //get Mana Vortex or Stables bonuses
  796. //same code is in the CGameHandler::buildStructure method
  797. if (visitingHero != nullptr)
  798. cb->visitCastleObjects(this, visitingHero);
  799. if (garrisonHero != nullptr)
  800. cb->visitCastleObjects(this, garrisonHero);
  801. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  802. {
  803. std::vector<SlotID> nativeCrits; //slots
  804. for (auto & elem : Slots())
  805. {
  806. if (elem.second->type->faction == subID) //native
  807. {
  808. nativeCrits.push_back(elem.first); //collect matching slots
  809. }
  810. }
  811. if (nativeCrits.size())
  812. {
  813. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  814. StackLocation sl(this, pos);
  815. const CCreature *c = getCreature(pos);
  816. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  817. {
  818. cb->changeStackCount(sl, c->growth);
  819. }
  820. else //upgrade
  821. {
  822. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  823. }
  824. }
  825. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  826. {
  827. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  828. if (!town->creatures[i].empty())
  829. {
  830. CreatureID c = town->creatures[i][0];
  831. SlotID n;
  832. TQuantity count = creatureGrowth(i);
  833. if (!count) // no dwelling
  834. count = VLC->creh->objects[c]->growth;
  835. {//no lower tiers or above current month
  836. if ((n = getSlotFor(c)).validSlot())
  837. {
  838. StackLocation sl(this, n);
  839. if (slotEmpty(n))
  840. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  841. else //add to existing
  842. cb->changeStackCount(sl, count);
  843. }
  844. }
  845. }
  846. }
  847. }
  848. }
  849. }
  850. /*
  851. int3 CGTownInstance::getSightCenter() const
  852. {
  853. return pos - int3(2,0,0);
  854. }
  855. */
  856. bool CGTownInstance::passableFor(PlayerColor color) const
  857. {
  858. if (!armedGarrison())//empty castle - anyone can visit
  859. return true;
  860. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  861. return false;
  862. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  863. }
  864. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  865. {
  866. offsets = {int3(-1,2,0), int3(-3,2,0)};
  867. }
  868. void CGTownInstance::mergeGarrisonOnSiege() const
  869. {
  870. auto getWeakestStackSlot = [&](ui64 powerLimit)
  871. {
  872. std::vector<SlotID> weakSlots;
  873. auto stacksList = visitingHero->stacks;
  874. std::pair<SlotID, CStackInstance *> pair;
  875. while(stacksList.size())
  876. {
  877. pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
  878. {
  879. return elem.second->getPower();
  880. });
  881. if(powerLimit > pair.second->getPower() &&
  882. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  883. {
  884. weakSlots.push_back(pair.first);
  885. stacksList.erase(pair.first);
  886. }
  887. else
  888. break;
  889. }
  890. if(weakSlots.size())
  891. return *std::max_element(weakSlots.begin(), weakSlots.end());
  892. return SlotID();
  893. };
  894. auto count = static_cast<int>(stacks.size());
  895. for(int i = 0; i < count; i++)
  896. {
  897. auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
  898. {
  899. ui64 power = elem.second->getPower();
  900. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  901. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  902. power += visitingHero->getStack(dst).getPower();
  903. return power;
  904. });
  905. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  906. if(dst.validSlot())
  907. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  908. else
  909. {
  910. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  911. if(dst.validSlot())
  912. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  913. }
  914. }
  915. }
  916. void CGTownInstance::removeCapitols (PlayerColor owner) const
  917. {
  918. if (hasCapitol()) // search if there's an older capitol
  919. {
  920. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  921. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  922. {
  923. if (*i != this && (*i)->hasCapitol())
  924. {
  925. RazeStructures rs;
  926. rs.tid = id;
  927. rs.bid.insert(BuildingID::CAPITOL);
  928. rs.destroyed = destroyed;
  929. cb->sendAndApply(&rs);
  930. return;
  931. }
  932. }
  933. }
  934. }
  935. void CGTownInstance::clearArmy() const
  936. {
  937. while(!stacks.empty())
  938. {
  939. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  940. }
  941. }
  942. int CGTownInstance::getBoatType() const
  943. {
  944. switch (town->faction->alignment)
  945. {
  946. case EAlignment::EVIL : return 0;
  947. case EAlignment::GOOD : return 1;
  948. case EAlignment::NEUTRAL : return 2;
  949. }
  950. assert(0);
  951. return -1;
  952. }
  953. int CGTownInstance::getMarketEfficiency() const
  954. {
  955. if(!hasBuiltSomeTradeBuilding())
  956. return 0;
  957. const PlayerState *p = cb->getPlayerState(tempOwner);
  958. assert(p);
  959. int marketCount = 0;
  960. for(const CGTownInstance *t : p->towns)
  961. if(t->hasBuiltSomeTradeBuilding())
  962. marketCount++;
  963. return marketCount;
  964. }
  965. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  966. {
  967. switch(mode)
  968. {
  969. case EMarketMode::RESOURCE_RESOURCE:
  970. case EMarketMode::RESOURCE_PLAYER:
  971. return hasBuilt(BuildingID::MARKETPLACE);
  972. case EMarketMode::ARTIFACT_RESOURCE:
  973. case EMarketMode::RESOURCE_ARTIFACT:
  974. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  975. case EMarketMode::CREATURE_RESOURCE:
  976. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  977. case EMarketMode::CREATURE_UNDEAD:
  978. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  979. case EMarketMode::RESOURCE_SKILL:
  980. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  981. default:
  982. assert(0);
  983. return false;
  984. }
  985. }
  986. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  987. {
  988. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  989. {
  990. std::vector<int> ret;
  991. for(const CArtifact *a : merchantArtifacts)
  992. if(a)
  993. ret.push_back(a->getId());
  994. else
  995. ret.push_back(-1);
  996. return ret;
  997. }
  998. else if ( mode == EMarketMode::RESOURCE_SKILL )
  999. {
  1000. return universitySkills;
  1001. }
  1002. else
  1003. return IMarket::availableItemsIds(mode);
  1004. }
  1005. void CGTownInstance::setType(si32 ID, si32 subID)
  1006. {
  1007. assert(ID == Obj::TOWN); // just in case
  1008. CGObjectInstance::setType(ID, subID);
  1009. town = (*VLC->townh)[subID]->town;
  1010. randomizeArmy(subID);
  1011. updateAppearance();
  1012. }
  1013. void CGTownInstance::updateAppearance()
  1014. {
  1015. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  1016. //FIXME: not the best way to do this
  1017. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  1018. if (app)
  1019. appearance = app;
  1020. }
  1021. std::string CGTownInstance::nodeName() const
  1022. {
  1023. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  1024. }
  1025. void CGTownInstance::deserializationFix()
  1026. {
  1027. attachTo(townAndVis);
  1028. //Hero is already handled by CGameState::attachArmedObjects
  1029. // if(visitingHero)
  1030. // visitingHero->attachTo(&townAndVis);
  1031. // if(garrisonHero)
  1032. // garrisonHero->attachTo(this);
  1033. }
  1034. void CGTownInstance::updateMoraleBonusFromArmy()
  1035. {
  1036. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  1037. if(!b)
  1038. {
  1039. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1040. addNewBonus(b);
  1041. }
  1042. if (garrisonHero)
  1043. {
  1044. b->val = 0;
  1045. CBonusSystemNode::treeHasChanged();
  1046. }
  1047. else
  1048. CArmedInstance::updateMoraleBonusFromArmy();
  1049. }
  1050. void CGTownInstance::recreateBuildingsBonuses()
  1051. {
  1052. BonusList bl;
  1053. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  1054. for(auto b : bl)
  1055. removeBonus(b);
  1056. for(const auto & bid : builtBuildings)
  1057. {
  1058. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  1059. continue;
  1060. auto building = town->buildings.at(bid);
  1061. if(building->buildingBonuses.empty())
  1062. continue;
  1063. for(auto & bonus : building->buildingBonuses)
  1064. {
  1065. if(bonus->limiter && bonus->effectRange == Bonus::ONLY_ENEMY_ARMY) //ONLY_ENEMY_ARMY is only mark for OppositeSide limiter to avoid extra dynamic_cast.
  1066. {
  1067. auto bCopy = std::make_shared<Bonus>(*bonus); //just a copy of the shared_ptr has been changed and reassigned.
  1068. bCopy->limiter = std::make_shared<OppositeSideLimiter>(this->getOwner());
  1069. addNewBonus(bCopy);
  1070. continue;
  1071. }
  1072. if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == ALL_CREATURES)
  1073. VLC->creh->addBonusForAllCreatures(bonus);
  1074. else
  1075. addNewBonus(bonus);
  1076. }
  1077. }
  1078. }
  1079. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1080. {
  1081. assert(!!visitingHero == !h);
  1082. if(h)
  1083. {
  1084. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1085. assert(p);
  1086. h->detachFrom(*p);
  1087. h->attachTo(townAndVis);
  1088. visitingHero = h;
  1089. h->visitedTown = this;
  1090. h->inTownGarrison = false;
  1091. }
  1092. else
  1093. {
  1094. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  1095. visitingHero->visitedTown = nullptr;
  1096. visitingHero->detachFrom(townAndVis);
  1097. visitingHero->attachTo(*p);
  1098. visitingHero = nullptr;
  1099. }
  1100. }
  1101. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1102. {
  1103. assert(!!garrisonHero == !h);
  1104. if(h)
  1105. {
  1106. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1107. assert(p);
  1108. h->detachFrom(*p);
  1109. h->attachTo(*this);
  1110. garrisonHero = h;
  1111. h->visitedTown = this;
  1112. h->inTownGarrison = true;
  1113. }
  1114. else
  1115. {
  1116. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  1117. garrisonHero->visitedTown = nullptr;
  1118. garrisonHero->inTownGarrison = false;
  1119. garrisonHero->detachFrom(*this);
  1120. garrisonHero->attachTo(*p);
  1121. garrisonHero = nullptr;
  1122. }
  1123. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1124. }
  1125. bool CGTownInstance::armedGarrison() const
  1126. {
  1127. return !stacks.empty() || garrisonHero;
  1128. }
  1129. const CTown * CGTownInstance::getTown() const
  1130. {
  1131. if(ID == Obj::RANDOM_TOWN)
  1132. return VLC->townh->randomTown;
  1133. else
  1134. {
  1135. if(nullptr == town)
  1136. {
  1137. return (*VLC->townh)[subID]->town;
  1138. }
  1139. else
  1140. return town;
  1141. }
  1142. }
  1143. int CGTownInstance::getTownLevel() const
  1144. {
  1145. // count all buildings that are not upgrades
  1146. int level = 0;
  1147. for(const auto & bid : builtBuildings)
  1148. {
  1149. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1150. level++;
  1151. }
  1152. return level;
  1153. }
  1154. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  1155. {
  1156. return townAndVis;
  1157. }
  1158. std::string CGTownInstance::getNameTranslated() const
  1159. {
  1160. return name;
  1161. }
  1162. void CGTownInstance::setNameTranslated( const std::string & newName )
  1163. {
  1164. name = newName;
  1165. }
  1166. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1167. {
  1168. if(garrisonHero)
  1169. return garrisonHero;
  1170. return this;
  1171. }
  1172. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1173. {
  1174. for(const auto building : bonusingBuildings)
  1175. {
  1176. if(building->getBuildingSubtype() == subId)
  1177. return building;
  1178. }
  1179. return nullptr;
  1180. }
  1181. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  1182. {
  1183. for(const auto & bid : builtBuildings)
  1184. {
  1185. if(town->buildings.at(bid)->IsTradeBuilding())
  1186. return true;
  1187. }
  1188. return false;
  1189. }
  1190. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1191. {
  1192. for(const auto & bid : builtBuildings)
  1193. {
  1194. if(town->buildings.at(bid)->subId == buildingID)
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  1200. {
  1201. return vstd::contains(builtBuildings, buildingID);
  1202. }
  1203. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  1204. {
  1205. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  1206. return hasBuilt(buildingID);
  1207. return false;
  1208. }
  1209. TResources CGTownInstance::getBuildingCost(BuildingID buildingID) const
  1210. {
  1211. if (vstd::contains(town->buildings, buildingID))
  1212. return town->buildings.at(buildingID)->resources;
  1213. else
  1214. {
  1215. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1216. return TResources();
  1217. }
  1218. }
  1219. CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool deep) const
  1220. {
  1221. const CBuilding * building = town->buildings.at(buildID);
  1222. //TODO: find better solution to prevent infinite loops
  1223. std::set<BuildingID> processed;
  1224. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1225. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1226. {
  1227. const CBuilding * build = town->buildings.at(id);
  1228. CBuilding::TRequired::OperatorAll requirements;
  1229. if (!hasBuilt(id))
  1230. {
  1231. if (deep)
  1232. requirements.expressions.push_back(id);
  1233. else
  1234. return id;
  1235. }
  1236. if(!vstd::contains(processed, id))
  1237. {
  1238. processed.insert(id);
  1239. if (build->upgrade != BuildingID::NONE)
  1240. requirements.expressions.push_back(dependTest(build->upgrade));
  1241. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1242. }
  1243. return requirements;
  1244. };
  1245. CBuilding::TRequired::OperatorAll requirements;
  1246. if (building->upgrade != BuildingID::NONE)
  1247. {
  1248. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1249. requirements.expressions.push_back(dependTest(upgr->bid));
  1250. processed.clear();
  1251. }
  1252. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1253. CBuilding::TRequired::Variant variant(requirements);
  1254. CBuilding::TRequired ret(variant);
  1255. ret.minimize();
  1256. return ret;
  1257. }
  1258. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1259. {
  1260. if(visitingHero == h)
  1261. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1262. else if(garrisonHero == h)
  1263. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1264. else
  1265. {
  1266. //should never ever happen
  1267. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  1268. throw std::runtime_error("internal error");
  1269. }
  1270. }
  1271. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  1272. {
  1273. if(result.winner == BattleSide::ATTACKER)
  1274. {
  1275. clearArmy();
  1276. onTownCaptured(hero->getOwner());
  1277. }
  1278. }
  1279. void CGTownInstance::onTownCaptured(const PlayerColor winner) const
  1280. {
  1281. setOwner(winner);
  1282. FoWChange fw;
  1283. fw.player = winner;
  1284. fw.mode = 1;
  1285. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  1286. cb->sendAndApply(& fw);
  1287. }
  1288. void CGTownInstance::afterAddToMap(CMap * map)
  1289. {
  1290. if(ID == Obj::TOWN)
  1291. map->towns.push_back(this);
  1292. }
  1293. void CGTownInstance::afterRemoveFromMap(CMap * map)
  1294. {
  1295. if (ID == Obj::TOWN)
  1296. vstd::erase_if_present(map->towns, this);
  1297. }
  1298. void CGTownInstance::reset()
  1299. {
  1300. CGTownInstance::merchantArtifacts.clear();
  1301. CGTownInstance::universitySkills.clear();
  1302. }
  1303. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1304. {
  1305. CGObjectInstance::serializeJsonOwner(handler);
  1306. CCreatureSet::serializeJson(handler, "army", 7);
  1307. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1308. handler.serializeString("name", name);
  1309. {
  1310. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1311. {
  1312. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  1313. if(rawId)
  1314. return rawId.get();
  1315. else
  1316. return -1;
  1317. };
  1318. auto encodeBuilding = [this](si32 index) -> std::string
  1319. {
  1320. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  1321. };
  1322. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1323. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1324. if(handler.saving)
  1325. {
  1326. bool customBuildings = false;
  1327. boost::logic::tribool hasFort(false);
  1328. for(const BuildingID & id : forbiddenBuildings)
  1329. {
  1330. buildingsLIC.none.insert(id);
  1331. customBuildings = true;
  1332. }
  1333. for(const BuildingID & id : builtBuildings)
  1334. {
  1335. if(id == BuildingID::DEFAULT)
  1336. continue;
  1337. const CBuilding * building = getTown()->buildings.at(id);
  1338. if(building->mode == CBuilding::BUILD_AUTO)
  1339. continue;
  1340. if(id == BuildingID::FORT)
  1341. hasFort = true;
  1342. buildingsLIC.all.insert(id);
  1343. customBuildings = true;
  1344. }
  1345. if(customBuildings)
  1346. handler.serializeLIC("buildings", buildingsLIC);
  1347. else
  1348. handler.serializeBool("hasFort",hasFort);
  1349. }
  1350. else
  1351. {
  1352. handler.serializeLIC("buildings", buildingsLIC);
  1353. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1354. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1355. {
  1356. builtBuildings.insert(BuildingID::DEFAULT);
  1357. bool hasFort = false;
  1358. handler.serializeBool("hasFort",hasFort);
  1359. if(hasFort)
  1360. builtBuildings.insert(BuildingID::FORT);
  1361. }
  1362. else
  1363. {
  1364. for(const si32 item : buildingsLIC.none)
  1365. forbiddenBuildings.insert(BuildingID(item));
  1366. for(const si32 item : buildingsLIC.all)
  1367. builtBuildings.insert(BuildingID(item));
  1368. }
  1369. }
  1370. }
  1371. {
  1372. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1373. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1374. if(handler.saving)
  1375. {
  1376. for(SpellID id : possibleSpells)
  1377. spellsLIC.any[id.num] = true;
  1378. for(SpellID id : obligatorySpells)
  1379. spellsLIC.all[id.num] = true;
  1380. }
  1381. handler.serializeLIC("spells", spellsLIC);
  1382. if(!handler.saving)
  1383. {
  1384. possibleSpells.clear();
  1385. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1386. {
  1387. if(spellsLIC.any[idx])
  1388. possibleSpells.push_back(SpellID(idx));
  1389. }
  1390. obligatorySpells.clear();
  1391. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1392. {
  1393. if(spellsLIC.all[idx])
  1394. obligatorySpells.push_back(SpellID(idx));
  1395. }
  1396. }
  1397. }
  1398. }
  1399. PlayerColor CGTownBuilding::getOwner() const
  1400. {
  1401. return town->getOwner();
  1402. }
  1403. int32_t CGTownBuilding::getObjGroupIndex() const
  1404. {
  1405. return -1;
  1406. }
  1407. int32_t CGTownBuilding::getObjTypeIndex() const
  1408. {
  1409. return 0;
  1410. }
  1411. int3 CGTownBuilding::visitablePos() const
  1412. {
  1413. return town->visitablePos();
  1414. }
  1415. int3 CGTownBuilding::getPosition() const
  1416. {
  1417. return town->getPosition();
  1418. }
  1419. COPWBonus::COPWBonus(BuildingID bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1420. {
  1421. bID = bid;
  1422. bType = subId;
  1423. town = cgTown;
  1424. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1425. }
  1426. void COPWBonus::setProperty(ui8 what, ui32 val)
  1427. {
  1428. switch (what)
  1429. {
  1430. case ObjProperty::VISITORS:
  1431. visitors.insert(val);
  1432. break;
  1433. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1434. visitors.clear();
  1435. break;
  1436. }
  1437. }
  1438. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  1439. {
  1440. ObjectInstanceID heroID = h->id;
  1441. if(town->hasBuilt(bID))
  1442. {
  1443. InfoWindow iw;
  1444. iw.player = h->tempOwner;
  1445. switch (this->bType)
  1446. {
  1447. case BuildingSubID::STABLES:
  1448. if(!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1449. {
  1450. GiveBonus gb;
  1451. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  1452. gb.id = heroID.getNum();
  1453. cb->giveHeroBonus(&gb);
  1454. SetMovePoints mp;
  1455. mp.val = 600;
  1456. mp.absolute = false;
  1457. mp.hid = heroID;
  1458. cb->setMovePoints(&mp);
  1459. iw.text << VLC->generaltexth->allTexts[580];
  1460. cb->showInfoDialog(&iw);
  1461. }
  1462. break;
  1463. case BuildingSubID::MANA_VORTEX:
  1464. if(visitors.empty())
  1465. {
  1466. if(h->mana < h->manaLimit() * 2)
  1467. cb->setManaPoints (heroID, 2 * h->manaLimit());
  1468. //TODO: investigate line below
  1469. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1470. iw.text << getVisitingBonusGreeting();
  1471. cb->showInfoDialog(&iw);
  1472. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1473. town->addHeroToStructureVisitors(h, indexOnTV);
  1474. }
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. CTownBonus::CTownBonus(BuildingID index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1480. {
  1481. bID = index;
  1482. bType = subId;
  1483. town = cgTown;
  1484. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1485. }
  1486. void CTownBonus::setProperty (ui8 what, ui32 val)
  1487. {
  1488. if(what == ObjProperty::VISITORS)
  1489. visitors.insert(ObjectInstanceID(val));
  1490. }
  1491. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1492. {
  1493. ObjectInstanceID heroID = h->id;
  1494. if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1495. {
  1496. si64 val = 0;
  1497. InfoWindow iw;
  1498. PrimarySkill::PrimarySkill what = PrimarySkill::NONE;
  1499. switch(bType)
  1500. {
  1501. case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
  1502. what = PrimarySkill::KNOWLEDGE;
  1503. val = 1;
  1504. iw.components.push_back(Component(Component::PRIM_SKILL, 3, 1, 0));
  1505. break;
  1506. case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
  1507. what = PrimarySkill::SPELL_POWER;
  1508. val = 1;
  1509. iw.components.push_back(Component(Component::PRIM_SKILL, 2, 1, 0));
  1510. break;
  1511. case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
  1512. what = PrimarySkill::ATTACK;
  1513. val = 1;
  1514. iw.components.push_back(Component(Component::PRIM_SKILL, 0, 1, 0));
  1515. break;
  1516. case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
  1517. what = PrimarySkill::EXPERIENCE;
  1518. val = static_cast<int>(h->calculateXp(1000));
  1519. iw.components.push_back(Component(Component::EXPERIENCE, 0, val, 0));
  1520. break;
  1521. case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
  1522. what = PrimarySkill::DEFENSE;
  1523. val = 1;
  1524. iw.components.push_back(Component(Component::PRIM_SKILL, 1, 1, 0));
  1525. break;
  1526. case BuildingSubID::CUSTOM_VISITING_BONUS:
  1527. const auto building = town->town->buildings.at(bID);
  1528. if(!h->hasBonusFrom(Bonus::TOWN_STRUCTURE, Bonus::getSid32(building->town->faction->getIndex(), building->bid)))
  1529. {
  1530. const auto & bonuses = building->onVisitBonuses;
  1531. applyBonuses(const_cast<CGHeroInstance *>(h), bonuses);
  1532. }
  1533. break;
  1534. }
  1535. if(what != PrimarySkill::NONE)
  1536. {
  1537. iw.player = cb->getOwner(heroID);
  1538. iw.text << getVisitingBonusGreeting();
  1539. cb->showInfoDialog(&iw);
  1540. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1541. town->addHeroToStructureVisitors(h, indexOnTV);
  1542. }
  1543. }
  1544. }
  1545. void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const
  1546. {
  1547. auto addToVisitors = false;
  1548. for(auto bonus : bonuses)
  1549. {
  1550. GiveBonus gb;
  1551. InfoWindow iw;
  1552. if(bonus->type == Bonus::TOWN_MAGIC_WELL)
  1553. {
  1554. if(h->mana >= h->manaLimit())
  1555. return;
  1556. cb->setManaPoints(h->id, h->manaLimit());
  1557. bonus->duration = Bonus::ONE_DAY;
  1558. }
  1559. gb.bonus = * bonus;
  1560. gb.id = h->id.getNum();
  1561. cb->giveHeroBonus(&gb);
  1562. if(bonus->duration == Bonus::PERMANENT)
  1563. addToVisitors = true;
  1564. iw.player = cb->getOwner(h->id);
  1565. iw.text << getCustomBonusGreeting(gb.bonus);
  1566. cb->showInfoDialog(&iw);
  1567. }
  1568. if(addToVisitors)
  1569. town->addHeroToStructureVisitors(h, indexOnTV);
  1570. }
  1571. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1572. : count(_count)
  1573. {
  1574. description = boost::str(boost::format(format) % count);
  1575. }
  1576. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  1577. : count(_count)
  1578. {
  1579. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1580. }
  1581. GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
  1582. : count(_count)
  1583. {
  1584. description = fullDescription;
  1585. }
  1586. CTownAndVisitingHero::CTownAndVisitingHero()
  1587. {
  1588. setNodeType(TOWN_AND_VISITOR);
  1589. }
  1590. int GrowthInfo::totalGrowth() const
  1591. {
  1592. int ret = 0;
  1593. for(const Entry &entry : entries)
  1594. ret += entry.count;
  1595. return ret;
  1596. }
  1597. const std::string CGTownBuilding::getVisitingBonusGreeting() const
  1598. {
  1599. auto bonusGreeting = town->town->getGreeting(bType);
  1600. if(!bonusGreeting.empty())
  1601. return bonusGreeting;
  1602. switch(bType)
  1603. {
  1604. case BuildingSubID::MANA_VORTEX:
  1605. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingManaVortex"));
  1606. break;
  1607. case BuildingSubID::KNOWLEDGE_VISITING_BONUS:
  1608. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingKnowledge"));
  1609. break;
  1610. case BuildingSubID::SPELL_POWER_VISITING_BONUS:
  1611. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingSpellPower"));
  1612. break;
  1613. case BuildingSubID::ATTACK_VISITING_BONUS:
  1614. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingAttack"));
  1615. break;
  1616. case BuildingSubID::EXPERIENCE_VISITING_BONUS:
  1617. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingExperience"));
  1618. break;
  1619. case BuildingSubID::DEFENSE_VISITING_BONUS:
  1620. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingDefence"));
  1621. break;
  1622. }
  1623. auto buildingName = town->town->getSpecialBuilding(bType)->getNameTranslated();
  1624. if(bonusGreeting.empty())
  1625. {
  1626. bonusGreeting = "Error: Bonus greeting for '%s' is not localized.";
  1627. logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->town->faction->getNameTranslated());
  1628. }
  1629. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1630. town->town->setGreeting(bType, bonusGreeting);
  1631. return bonusGreeting;
  1632. }
  1633. const std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const
  1634. {
  1635. if(bonus.type == Bonus::TOWN_MAGIC_WELL)
  1636. {
  1637. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingInTownMagicWell"));
  1638. auto buildingName = town->town->getSpecialBuilding(bType)->getNameTranslated();
  1639. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1640. return bonusGreeting;
  1641. }
  1642. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingCustomBonus")); //"%s gives you +%d %s%s"
  1643. std::string param = "";
  1644. std::string until = "";
  1645. if(bonus.type == Bonus::MORALE)
  1646. param = VLC->generaltexth->allTexts[384];
  1647. else if(bonus.type == Bonus::LUCK)
  1648. param = VLC->generaltexth->allTexts[385];
  1649. until = bonus.duration == (ui16)Bonus::ONE_BATTLE
  1650. ? VLC->generaltexth->translate("vcmi.townHall.greetingCustomUntil") : ".";
  1651. boost::format fmt = boost::format(bonusGreeting) % bonus.description % bonus.val % param % until;
  1652. std::string greeting = fmt.str();
  1653. return greeting;
  1654. }
  1655. VCMI_LIB_NAMESPACE_END