CGTownInstance.cpp 51 KB

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