CGTownInstance.cpp 50 KB

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