CGTownInstance.cpp 52 KB

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