CGTownInstance.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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 "CGTownBuilding.h"
  13. #include "../spells/CSpellHandler.h"
  14. #include "../bonuses/Bonus.h"
  15. #include "../battle/IBattleInfoCallback.h"
  16. #include "../CConfigHandler.h"
  17. #include "../texts/CGeneralTextHandler.h"
  18. #include "../IGameCallback.h"
  19. #include "../gameState/CGameState.h"
  20. #include "../mapping/CMap.h"
  21. #include "../CPlayerState.h"
  22. #include "../StartInfo.h"
  23. #include "../TerrainHandler.h"
  24. #include "../entities/building/CBuilding.h"
  25. #include "../entities/faction/CTownHandler.h"
  26. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  27. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  28. #include "../mapObjects/CGHeroInstance.h"
  29. #include "../modding/ModScope.h"
  30. #include "../networkPacks/StackLocation.h"
  31. #include "../networkPacks/PacksForClient.h"
  32. #include "../networkPacks/PacksForClientBattle.h"
  33. #include "../serializer/JsonSerializeFormat.h"
  34. #include <vstd/RNG.h>
  35. VCMI_LIB_NAMESPACE_BEGIN
  36. int CGTownInstance::getSightRadius() const //returns sight distance
  37. {
  38. auto ret = CBuilding::HEIGHT_NO_TOWER;
  39. for(const auto & bid : builtBuildings)
  40. {
  41. if(bid.IsSpecialOrGrail())
  42. {
  43. auto height = town->buildings.at(bid)->height;
  44. if(ret < height)
  45. ret = height;
  46. }
  47. }
  48. return ret;
  49. }
  50. void CGTownInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  51. {
  52. ///this is freakin' overcomplicated solution
  53. switch (what)
  54. {
  55. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  56. bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::VISITORS, visitingHero->id);
  57. break;
  58. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  59. bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0));
  60. break;
  61. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  62. bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::VISITORS, garrisonHero->id);
  63. break;
  64. case ObjProperty::BONUS_VALUE_FIRST:
  65. bonusValue.first = identifier.getNum();
  66. break;
  67. case ObjProperty::BONUS_VALUE_SECOND:
  68. bonusValue.second = identifier.getNum();
  69. break;
  70. }
  71. }
  72. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  73. {
  74. if (hasBuilt(BuildingID::CASTLE))
  75. return CASTLE;
  76. if (hasBuilt(BuildingID::CITADEL))
  77. return CITADEL;
  78. if (hasBuilt(BuildingID::FORT))
  79. return FORT;
  80. return NONE;
  81. }
  82. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  83. {
  84. if (hasBuilt(BuildingID::CAPITOL))
  85. return 3;
  86. if (hasBuilt(BuildingID::CITY_HALL))
  87. return 2;
  88. if (hasBuilt(BuildingID::TOWN_HALL))
  89. return 1;
  90. if (hasBuilt(BuildingID::VILLAGE_HALL))
  91. return 0;
  92. return -1;
  93. }
  94. int CGTownInstance::mageGuildLevel() const
  95. {
  96. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  97. return 5;
  98. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  99. return 4;
  100. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  101. return 3;
  102. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  103. return 2;
  104. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  105. return 1;
  106. return 0;
  107. }
  108. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  109. {
  110. return town->hordeLvl.at(HID);
  111. }
  112. int CGTownInstance::creatureGrowth(const int & level) const
  113. {
  114. return getGrowthInfo(level).totalGrowth();
  115. }
  116. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  117. {
  118. GrowthInfo ret;
  119. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  120. return ret;
  121. if (creatures[level].second.empty())
  122. return ret; //no dwelling
  123. const Creature *creature = creatures[level].second.back().toEntity(VLC);
  124. const int base = creature->getGrowth();
  125. int castleBonus = 0;
  126. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  127. if (hasBuilt(BuildingID::CASTLE))
  128. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  129. else if (hasBuilt(BuildingID::CITADEL))
  130. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  131. if(town->hordeLvl.at(0) == level)//horde 1
  132. if(hasBuilt(BuildingID::HORDE_1))
  133. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  134. if(town->hordeLvl.at(1) == level)//horde 2
  135. if(hasBuilt(BuildingID::HORDE_2))
  136. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  137. //statue-of-legion-like bonus: % to base+castle
  138. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(BonusType::CREATURE_GROWTH_PERCENT));
  139. for(const auto & b : *bonuses2)
  140. {
  141. const auto growth = b->val * (base + castleBonus) / 100;
  142. if (growth)
  143. {
  144. ret.entries.emplace_back(growth, b->Description(growth));
  145. }
  146. }
  147. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  148. // Note: bonus uses 1-based levels (Pikeman is level 1), town list uses 0-based (Pikeman in 0-th creatures entry)
  149. TConstBonusListPtr bonuses = getBonuses(Selector::typeSubtype(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(level+1)));
  150. for(const auto & b : *bonuses)
  151. ret.entries.emplace_back(b->val, b->Description());
  152. int dwellingBonus = 0;
  153. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  154. {
  155. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  156. }
  157. if(dwellingBonus)
  158. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  159. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  160. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  161. return ret;
  162. }
  163. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  164. {
  165. int totalBonus = 0;
  166. for (const auto& dwelling : dwellings)
  167. {
  168. for (const auto& creature : dwelling->creatures)
  169. {
  170. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  171. }
  172. }
  173. return totalBonus;
  174. }
  175. TResources CGTownInstance::dailyIncome() const
  176. {
  177. TResources ret;
  178. for(const auto & p : town->buildings)
  179. {
  180. BuildingID buildingUpgrade;
  181. for(const auto & p2 : town->buildings)
  182. {
  183. if (p2.second->upgrade == p.first)
  184. {
  185. buildingUpgrade = p2.first;
  186. }
  187. }
  188. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  189. {
  190. ret += p.second->produce;
  191. }
  192. }
  193. auto playerSettings = cb->gameState()->scenarioOps->getIthPlayersSettings(getOwner());
  194. for(TResources::nziterator it(ret); it.valid(); it++)
  195. ret[it->resType] = ret[it->resType] * playerSettings.handicap.percentIncome / 100;
  196. return ret;
  197. }
  198. bool CGTownInstance::hasFort() const
  199. {
  200. return hasBuilt(BuildingID::FORT);
  201. }
  202. bool CGTownInstance::hasCapitol() const
  203. {
  204. return hasBuilt(BuildingID::CAPITOL);
  205. }
  206. CGTownInstance::CGTownInstance(IGameCallback *cb):
  207. CGDwelling(cb),
  208. town(nullptr),
  209. built(0),
  210. destroyed(0),
  211. identifier(0),
  212. alignmentToPlayer(PlayerColor::NEUTRAL)
  213. {
  214. this->setNodeType(CBonusSystemNode::TOWN);
  215. }
  216. CGTownInstance::~CGTownInstance()
  217. {
  218. for (auto & elem : bonusingBuildings)
  219. delete elem;
  220. }
  221. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  222. {
  223. if(checkGuild && mageGuildLevel() < level)
  224. return 0;
  225. int ret = 6 - level; //how many spells are available at this level
  226. if (hasBuilt(BuildingSubID::LIBRARY))
  227. ret++;
  228. return ret;
  229. }
  230. bool CGTownInstance::needsLastStack() const
  231. {
  232. return garrisonHero != nullptr;
  233. }
  234. void CGTownInstance::setOwner(const PlayerColor & player) const
  235. {
  236. removeCapitols(player);
  237. cb->setOwner(this, player);
  238. }
  239. void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  240. {
  241. for (auto building : bonusingBuildings)
  242. building->blockingDialogAnswered(hero, answer);
  243. }
  244. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  245. {
  246. if(cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)
  247. {
  248. if(armedGarrison() || visitingHero)
  249. {
  250. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  251. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  252. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  253. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  254. {
  255. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  256. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  257. if(nodeSiege == (CBonusSystemNode *)this)
  258. cb->swapGarrisonOnSiege(this->id);
  259. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  260. }
  261. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  262. }
  263. else
  264. {
  265. auto heroColor = h->getOwner();
  266. onTownCaptured(heroColor);
  267. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  268. {
  269. return; //we just won game, we do not need to perform any extra actions
  270. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  271. }
  272. cb->heroVisitCastle(this, h);
  273. }
  274. }
  275. else if(h->visitablePos() == visitablePos())
  276. {
  277. bool commander_recover = h->commander && !h->commander->alive;
  278. if (commander_recover) // rise commander from dead
  279. {
  280. SetCommanderProperty scp;
  281. scp.heroid = h->id;
  282. scp.which = SetCommanderProperty::ALIVE;
  283. scp.amount = 1;
  284. cb->sendAndApply(&scp);
  285. }
  286. cb->heroVisitCastle(this, h);
  287. // TODO(vmarkovtsev): implement payment for rising the commander
  288. if (commander_recover) // info window about commander
  289. {
  290. InfoWindow iw;
  291. iw.player = h->tempOwner;
  292. iw.text.appendRawString(h->commander->getName());
  293. iw.components.emplace_back(ComponentType::CREATURE, h->commander->getId(), h->commander->getCount());
  294. cb->showInfoDialog(&iw);
  295. }
  296. }
  297. else
  298. {
  299. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), getNameTranslated());
  300. }
  301. }
  302. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  303. {
  304. //FIXME: find out why this issue appears on random maps
  305. if(visitingHero == h)
  306. {
  307. cb->stopHeroVisitCastle(this, h);
  308. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), getNameTranslated());
  309. }
  310. else
  311. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), getNameTranslated());
  312. }
  313. std::string CGTownInstance::getObjectName() const
  314. {
  315. return getNameTranslated() + ", " + town->faction->getNameTranslated();
  316. }
  317. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  318. {
  319. return town->getBuildingType(subId) != BuildingID::NONE;
  320. }
  321. void CGTownInstance::initOverriddenBids()
  322. {
  323. for(const auto & bid : builtBuildings)
  324. {
  325. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  326. for(const auto & overrideIt : overrideThem)
  327. overriddenBuildings.insert(overrideIt);
  328. }
  329. }
  330. bool CGTownInstance::isBonusingBuildingAdded(BuildingID bid) const
  331. {
  332. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  333. {
  334. return building->getBuildingType() == bid;
  335. });
  336. return present != bonusingBuildings.end();
  337. }
  338. void CGTownInstance::addTownBonuses(vstd::RNG & rand)
  339. {
  340. for(const auto & kvp : town->buildings)
  341. {
  342. if(vstd::contains(overriddenBuildings, kvp.first))
  343. continue;
  344. if(kvp.second->IsVisitingBonus())
  345. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  346. if(kvp.second->IsWeekBonus())
  347. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  348. if(kvp.second->subId == BuildingSubID::CUSTOM_VISITING_REWARD)
  349. bonusingBuildings.push_back(new CTownRewardableBuilding(kvp.second->bid, kvp.second->subId, this, rand));
  350. }
  351. }
  352. DamageRange CGTownInstance::getTowerDamageRange() const
  353. {
  354. assert(hasBuilt(BuildingID::CASTLE));
  355. // http://heroes.thelazy.net/wiki/Arrow_tower
  356. // base damage, irregardless of town level
  357. static constexpr int baseDamage = 6;
  358. // extra damage, for each building in town
  359. static constexpr int extraDamage = 1;
  360. const int minDamage = baseDamage + extraDamage * getTownLevel();
  361. return {
  362. minDamage,
  363. minDamage * 2
  364. };
  365. }
  366. DamageRange CGTownInstance::getKeepDamageRange() const
  367. {
  368. assert(hasBuilt(BuildingID::CITADEL));
  369. // http://heroes.thelazy.net/wiki/Arrow_tower
  370. // base damage, irregardless of town level
  371. static constexpr int baseDamage = 10;
  372. // extra damage, for each building in town
  373. static constexpr int extraDamage = 2;
  374. const int minDamage = baseDamage + extraDamage * getTownLevel();
  375. return {
  376. minDamage,
  377. minDamage * 2
  378. };
  379. }
  380. void CGTownInstance::deleteTownBonus(BuildingID bid)
  381. {
  382. size_t i = 0;
  383. CGTownBuilding * freeIt = nullptr;
  384. for(i = 0; i != bonusingBuildings.size(); i++)
  385. {
  386. if(bonusingBuildings[i]->getBuildingType() == bid)
  387. {
  388. freeIt = bonusingBuildings[i];
  389. break;
  390. }
  391. }
  392. if(freeIt == nullptr)
  393. return;
  394. auto building = town->buildings.at(bid);
  395. auto isVisitingBonus = building->IsVisitingBonus();
  396. auto isWeekBonus = building->IsWeekBonus();
  397. if(!isVisitingBonus && !isWeekBonus)
  398. return;
  399. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  400. delete freeIt;
  401. }
  402. FactionID CGTownInstance::randomizeFaction(vstd::RNG & rand)
  403. {
  404. if(getOwner().isValidPlayer())
  405. return cb->gameState()->scenarioOps->getIthPlayersSettings(getOwner()).castle;
  406. if(alignmentToPlayer.isValidPlayer())
  407. return cb->gameState()->scenarioOps->getIthPlayersSettings(alignmentToPlayer).castle;
  408. std::vector<FactionID> potentialPicks;
  409. for (FactionID faction(0); faction < FactionID(VLC->townh->size()); ++faction)
  410. if (VLC->factions()->getById(faction)->hasTown())
  411. potentialPicks.push_back(faction);
  412. assert(!potentialPicks.empty());
  413. return *RandomGeneratorUtil::nextItem(potentialPicks, rand);
  414. }
  415. void CGTownInstance::pickRandomObject(vstd::RNG & rand)
  416. {
  417. assert(ID == MapObjectID::TOWN || ID == MapObjectID::RANDOM_TOWN);
  418. if (ID == MapObjectID::RANDOM_TOWN)
  419. {
  420. ID = MapObjectID::TOWN;
  421. subID = randomizeFaction(rand);
  422. }
  423. assert(ID == Obj::TOWN); // just in case
  424. setType(ID, subID);
  425. town = (*VLC->townh)[getFaction()]->town;
  426. randomizeArmy(getFaction());
  427. updateAppearance();
  428. }
  429. void CGTownInstance::initObj(vstd::RNG & rand) ///initialize town structures
  430. {
  431. blockVisit = true;
  432. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  433. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  434. else
  435. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  436. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  437. {
  438. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST + level);
  439. int upgradeNum = 0;
  440. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  441. {
  442. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  443. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  444. }
  445. }
  446. initOverriddenBids();
  447. addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector.
  448. recreateBuildingsBonuses();
  449. updateAppearance();
  450. }
  451. void CGTownInstance::newTurn(vstd::RNG & rand) const
  452. {
  453. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  454. {
  455. //give resources if there's a Mystic Pond
  456. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  457. && cb->getDate(Date::DAY) != 1
  458. && (tempOwner.isValidPlayer())
  459. )
  460. {
  461. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  462. resID = (resID==2)?1:resID;
  463. int resVal = rand.nextInt(1, 4);//with size 1..4
  464. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  465. cb->setObjPropertyValue(id, ObjProperty::BONUS_VALUE_FIRST, resID);
  466. cb->setObjPropertyValue(id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  467. }
  468. for(const auto * manaVortex : getBonusingBuildings(BuildingSubID::MANA_VORTEX))
  469. cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  470. //get Mana Vortex or Stables bonuses
  471. //same code is in the CGameHandler::buildStructure method
  472. if (garrisonHero != nullptr) //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order
  473. cb->visitCastleObjects(this, garrisonHero);
  474. if (visitingHero != nullptr)
  475. cb->visitCastleObjects(this, visitingHero);
  476. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  477. {
  478. std::vector<SlotID> nativeCrits; //slots
  479. for(const auto & elem : Slots())
  480. {
  481. if (elem.second->type->getFaction() == getFaction()) //native
  482. {
  483. nativeCrits.push_back(elem.first); //collect matching slots
  484. }
  485. }
  486. if(!nativeCrits.empty())
  487. {
  488. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  489. StackLocation sl(this, pos);
  490. const CCreature *c = getCreature(pos);
  491. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  492. {
  493. cb->changeStackCount(sl, c->getGrowth());
  494. }
  495. else //upgrade
  496. {
  497. cb->changeStackType(sl, c->upgrades.begin()->toCreature());
  498. }
  499. }
  500. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  501. {
  502. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  503. if (!town->creatures[i].empty())
  504. {
  505. CreatureID c = town->creatures[i][0];
  506. SlotID n;
  507. TQuantity count = creatureGrowth(i);
  508. if (!count) // no dwelling
  509. count = VLC->creatures()->getById(c)->getGrowth();
  510. {//no lower tiers or above current month
  511. if ((n = getSlotFor(c)).validSlot())
  512. {
  513. StackLocation sl(this, n);
  514. if (slotEmpty(n))
  515. cb->insertNewStack(sl, c.toCreature(), count);
  516. else //add to existing
  517. cb->changeStackCount(sl, count);
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. for(const auto * rewardableBuilding : getBonusingBuildings(BuildingSubID::CUSTOM_VISITING_REWARD))
  525. rewardableBuilding->newTurn(rand);
  526. }
  527. /*
  528. int3 CGTownInstance::getSightCenter() const
  529. {
  530. return pos - int3(2,0,0);
  531. }
  532. */
  533. bool CGTownInstance::passableFor(PlayerColor color) const
  534. {
  535. if (!armedGarrison())//empty castle - anyone can visit
  536. return true;
  537. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  538. return false;
  539. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  540. }
  541. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  542. {
  543. offsets = {int3(-1,2,0), int3(+1,2,0)};
  544. }
  545. CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
  546. {
  547. if (!hasBuilt(BuildingID::SHIPYARD))
  548. return EGeneratorState::UNKNOWN;
  549. return IShipyard::shipyardStatus();
  550. }
  551. const IObjectInterface * CGTownInstance::getObject() const
  552. {
  553. return this;
  554. }
  555. void CGTownInstance::mergeGarrisonOnSiege() const
  556. {
  557. auto getWeakestStackSlot = [&](ui64 powerLimit)
  558. {
  559. std::vector<SlotID> weakSlots;
  560. auto stacksList = visitingHero->stacks;
  561. std::pair<SlotID, CStackInstance *> pair;
  562. while(!stacksList.empty())
  563. {
  564. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  565. if(powerLimit > pair.second->getPower() &&
  566. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  567. {
  568. weakSlots.push_back(pair.first);
  569. stacksList.erase(pair.first);
  570. }
  571. else
  572. break;
  573. }
  574. if(!weakSlots.empty())
  575. return *std::max_element(weakSlots.begin(), weakSlots.end());
  576. return SlotID();
  577. };
  578. auto count = static_cast<int>(stacks.size());
  579. for(int i = 0; i < count; i++)
  580. {
  581. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  582. {
  583. ui64 power = elem.second->getPower();
  584. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  585. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  586. power += visitingHero->getStack(dst).getPower();
  587. return power;
  588. });
  589. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  590. if(dst.validSlot())
  591. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  592. else
  593. {
  594. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  595. if(dst.validSlot())
  596. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  597. }
  598. }
  599. }
  600. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  601. {
  602. if (hasCapitol()) // search if there's an older capitol
  603. {
  604. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  605. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  606. {
  607. if (*i != this && (*i)->hasCapitol())
  608. {
  609. RazeStructures rs;
  610. rs.tid = id;
  611. rs.bid.insert(BuildingID::CAPITOL);
  612. rs.destroyed = destroyed;
  613. cb->sendAndApply(&rs);
  614. return;
  615. }
  616. }
  617. }
  618. }
  619. void CGTownInstance::clearArmy() const
  620. {
  621. while(!stacks.empty())
  622. {
  623. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  624. }
  625. }
  626. BoatId CGTownInstance::getBoatType() const
  627. {
  628. return town->faction->boatType;
  629. }
  630. int CGTownInstance::getMarketEfficiency() const
  631. {
  632. if(!hasBuiltSomeTradeBuilding())
  633. return 0;
  634. const PlayerState *p = cb->getPlayerState(tempOwner);
  635. assert(p);
  636. int marketCount = 0;
  637. for(const CGTownInstance *t : p->towns)
  638. if(t->hasBuiltSomeTradeBuilding())
  639. marketCount++;
  640. return marketCount;
  641. }
  642. bool CGTownInstance::allowsTrade(EMarketMode mode) const
  643. {
  644. switch(mode)
  645. {
  646. case EMarketMode::RESOURCE_RESOURCE:
  647. case EMarketMode::RESOURCE_PLAYER:
  648. return hasBuilt(BuildingID::MARKETPLACE);
  649. case EMarketMode::ARTIFACT_RESOURCE:
  650. case EMarketMode::RESOURCE_ARTIFACT:
  651. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  652. case EMarketMode::CREATURE_RESOURCE:
  653. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  654. case EMarketMode::CREATURE_UNDEAD:
  655. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  656. case EMarketMode::RESOURCE_SKILL:
  657. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  658. case EMarketMode::CREATURE_EXP:
  659. case EMarketMode::ARTIFACT_EXP:
  660. return false;
  661. default:
  662. assert(0);
  663. return false;
  664. }
  665. }
  666. std::vector<TradeItemBuy> CGTownInstance::availableItemsIds(EMarketMode mode) const
  667. {
  668. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  669. {
  670. std::vector<TradeItemBuy> ret;
  671. for(const CArtifact *a : cb->gameState()->map->townMerchantArtifacts)
  672. if(a)
  673. ret.push_back(a->getId());
  674. else
  675. ret.push_back(ArtifactID{});
  676. return ret;
  677. }
  678. else if ( mode == EMarketMode::RESOURCE_SKILL )
  679. {
  680. return cb->gameState()->map->townUniversitySkills;
  681. }
  682. else
  683. return IMarket::availableItemsIds(mode);
  684. }
  685. void CGTownInstance::updateAppearance()
  686. {
  687. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  688. //FIXME: not the best way to do this
  689. auto app = getObjectHandler()->getOverride(terrain, this);
  690. if (app)
  691. appearance = app;
  692. }
  693. std::string CGTownInstance::nodeName() const
  694. {
  695. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + getNameTranslated();
  696. }
  697. void CGTownInstance::deserializationFix()
  698. {
  699. attachTo(townAndVis);
  700. //Hero is already handled by CGameState::attachArmedObjects
  701. // if(visitingHero)
  702. // visitingHero->attachTo(&townAndVis);
  703. // if(garrisonHero)
  704. // garrisonHero->attachTo(this);
  705. }
  706. void CGTownInstance::updateMoraleBonusFromArmy()
  707. {
  708. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  709. if(!b)
  710. {
  711. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
  712. addNewBonus(b);
  713. }
  714. if (garrisonHero)
  715. {
  716. b->val = 0;
  717. CBonusSystemNode::treeHasChanged();
  718. }
  719. else
  720. CArmedInstance::updateMoraleBonusFromArmy();
  721. }
  722. void CGTownInstance::recreateBuildingsBonuses()
  723. {
  724. BonusList bl;
  725. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  726. for(const auto & b : bl)
  727. removeBonus(b);
  728. for(const auto & bid : builtBuildings)
  729. {
  730. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  731. continue;
  732. auto building = town->buildings.at(bid);
  733. if(building->buildingBonuses.empty())
  734. continue;
  735. for(auto & bonus : building->buildingBonuses)
  736. addNewBonus(bonus);
  737. }
  738. }
  739. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  740. {
  741. if(visitingHero.get() == h)
  742. return;
  743. if(h)
  744. {
  745. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  746. assert(p);
  747. h->detachFrom(*p);
  748. h->attachTo(townAndVis);
  749. visitingHero = h;
  750. h->visitedTown = this;
  751. h->inTownGarrison = false;
  752. }
  753. else
  754. {
  755. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  756. visitingHero->visitedTown = nullptr;
  757. visitingHero->detachFrom(townAndVis);
  758. visitingHero->attachTo(*p);
  759. visitingHero = nullptr;
  760. }
  761. }
  762. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  763. {
  764. if(garrisonHero.get() == h)
  765. return;
  766. if(h)
  767. {
  768. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  769. assert(p);
  770. h->detachFrom(*p);
  771. h->attachTo(*this);
  772. garrisonHero = h;
  773. h->visitedTown = this;
  774. h->inTownGarrison = true;
  775. }
  776. else
  777. {
  778. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  779. garrisonHero->visitedTown = nullptr;
  780. garrisonHero->inTownGarrison = false;
  781. garrisonHero->detachFrom(*this);
  782. garrisonHero->attachTo(*p);
  783. garrisonHero = nullptr;
  784. }
  785. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  786. }
  787. bool CGTownInstance::armedGarrison() const
  788. {
  789. return !stacks.empty() || garrisonHero;
  790. }
  791. const CTown * CGTownInstance::getTown() const
  792. {
  793. if(ID == Obj::RANDOM_TOWN)
  794. return VLC->townh->randomTown;
  795. else
  796. {
  797. if(nullptr == town)
  798. {
  799. return (*VLC->townh)[getFaction()]->town;
  800. }
  801. else
  802. return town;
  803. }
  804. }
  805. int CGTownInstance::getTownLevel() const
  806. {
  807. // count all buildings that are not upgrades
  808. int level = 0;
  809. for(const auto & bid : builtBuildings)
  810. {
  811. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  812. level++;
  813. }
  814. return level;
  815. }
  816. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  817. {
  818. return townAndVis;
  819. }
  820. std::string CGTownInstance::getNameTranslated() const
  821. {
  822. return VLC->generaltexth->translate(nameTextId);
  823. }
  824. std::string CGTownInstance::getNameTextID() const
  825. {
  826. return nameTextId;
  827. }
  828. void CGTownInstance::setNameTextId( const std::string & newName )
  829. {
  830. nameTextId = newName;
  831. }
  832. const CArmedInstance * CGTownInstance::getUpperArmy() const
  833. {
  834. if(garrisonHero)
  835. return garrisonHero;
  836. return this;
  837. }
  838. std::vector<const CGTownBuilding *> CGTownInstance::getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const
  839. {
  840. std::vector<const CGTownBuilding *> ret;
  841. for(auto * const building : bonusingBuildings)
  842. {
  843. if(building->getBuildingSubtype() == subId)
  844. ret.push_back(building);
  845. }
  846. return ret;
  847. }
  848. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  849. {
  850. for(const auto & bid : builtBuildings)
  851. {
  852. if(town->buildings.at(bid)->IsTradeBuilding())
  853. return true;
  854. }
  855. return false;
  856. }
  857. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  858. {
  859. for(const auto & bid : builtBuildings)
  860. {
  861. if(town->buildings.at(bid)->subId == buildingID)
  862. return true;
  863. }
  864. return false;
  865. }
  866. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  867. {
  868. return vstd::contains(builtBuildings, buildingID);
  869. }
  870. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, FactionID townID) const
  871. {
  872. if (townID == town->faction->getId() || townID == FactionID::ANY)
  873. return hasBuilt(buildingID);
  874. return false;
  875. }
  876. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  877. {
  878. if (vstd::contains(town->buildings, buildingID))
  879. return town->buildings.at(buildingID)->resources;
  880. else
  881. {
  882. logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), pos.toString(), buildingID.toEnum());
  883. return TResources();
  884. }
  885. }
  886. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  887. {
  888. const CBuilding * building = town->buildings.at(buildID);
  889. //TODO: find better solution to prevent infinite loops
  890. std::set<BuildingID> processed;
  891. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  892. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  893. {
  894. if (town->buildings.count(id) == 0)
  895. {
  896. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  897. return CBuilding::TRequired::OperatorAll();
  898. }
  899. const CBuilding * build = town->buildings.at(id);
  900. CBuilding::TRequired::OperatorAll requirements;
  901. if (!hasBuilt(id))
  902. {
  903. if (deep)
  904. requirements.expressions.emplace_back(id);
  905. else
  906. return id;
  907. }
  908. if(!vstd::contains(processed, id))
  909. {
  910. processed.insert(id);
  911. if (build->upgrade != BuildingID::NONE)
  912. requirements.expressions.push_back(dependTest(build->upgrade));
  913. requirements.expressions.push_back(build->requirements.morph(dependTest));
  914. }
  915. return requirements;
  916. };
  917. CBuilding::TRequired::OperatorAll requirements;
  918. if (building->upgrade != BuildingID::NONE)
  919. {
  920. const CBuilding * upgr = town->buildings.at(building->upgrade);
  921. requirements.expressions.push_back(dependTest(upgr->bid));
  922. processed.clear();
  923. }
  924. requirements.expressions.push_back(building->requirements.morph(dependTest));
  925. CBuilding::TRequired::Variant variant(requirements);
  926. CBuilding::TRequired ret(variant);
  927. ret.minimize();
  928. return ret;
  929. }
  930. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  931. {
  932. if(visitingHero == h)
  933. cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  934. else if(garrisonHero == h)
  935. cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  936. else
  937. {
  938. //should never ever happen
  939. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  940. throw std::runtime_error("unexpected hero in CGTownInstance::addHeroToStructureVisitors");
  941. }
  942. }
  943. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  944. {
  945. if(result.winner == BattleSide::ATTACKER)
  946. {
  947. clearArmy();
  948. onTownCaptured(hero->getOwner());
  949. }
  950. }
  951. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  952. {
  953. setOwner(winner);
  954. cb->changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  955. }
  956. void CGTownInstance::afterAddToMap(CMap * map)
  957. {
  958. map->towns.emplace_back(this);
  959. }
  960. void CGTownInstance::afterRemoveFromMap(CMap * map)
  961. {
  962. vstd::erase_if_present(map->towns, this);
  963. }
  964. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  965. {
  966. CGObjectInstance::serializeJsonOwner(handler);
  967. if(!handler.saving)
  968. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  969. CArmedInstance::serializeJsonOptions(handler);
  970. handler.serializeString("name", nameTextId);
  971. {
  972. auto decodeBuilding = [this](const std::string & identifier) -> si32
  973. {
  974. auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  975. if(rawId)
  976. return rawId.value();
  977. else
  978. return -1;
  979. };
  980. auto encodeBuilding = [this](si32 index) -> std::string
  981. {
  982. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  983. };
  984. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  985. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  986. if(handler.saving)
  987. {
  988. bool customBuildings = false;
  989. boost::logic::tribool hasFort(false);
  990. for(const BuildingID & id : forbiddenBuildings)
  991. {
  992. buildingsLIC.none.insert(id.getNum());
  993. customBuildings = true;
  994. }
  995. for(const BuildingID & id : builtBuildings)
  996. {
  997. if(id == BuildingID::DEFAULT)
  998. continue;
  999. const CBuilding * building = getTown()->buildings.at(id);
  1000. if(building->mode == CBuilding::BUILD_AUTO)
  1001. continue;
  1002. if(id == BuildingID::FORT)
  1003. hasFort = true;
  1004. buildingsLIC.all.insert(id.getNum());
  1005. customBuildings = true;
  1006. }
  1007. if(customBuildings)
  1008. handler.serializeLIC("buildings", buildingsLIC);
  1009. else
  1010. handler.serializeBool("hasFort",hasFort);
  1011. }
  1012. else
  1013. {
  1014. handler.serializeLIC("buildings", buildingsLIC);
  1015. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1016. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1017. {
  1018. builtBuildings.insert(BuildingID::DEFAULT);
  1019. bool hasFort = false;
  1020. handler.serializeBool("hasFort",hasFort);
  1021. if(hasFort)
  1022. builtBuildings.insert(BuildingID::FORT);
  1023. }
  1024. else
  1025. {
  1026. for(const si32 item : buildingsLIC.none)
  1027. forbiddenBuildings.insert(BuildingID(item));
  1028. for(const si32 item : buildingsLIC.all)
  1029. builtBuildings.insert(BuildingID(item));
  1030. }
  1031. }
  1032. }
  1033. {
  1034. handler.serializeIdArray( "possibleSpells", possibleSpells);
  1035. handler.serializeIdArray( "obligatorySpells", obligatorySpells);
  1036. }
  1037. }
  1038. FactionID CGTownInstance::getFaction() const
  1039. {
  1040. return FactionID(subID.getNum());
  1041. }
  1042. TerrainId CGTownInstance::getNativeTerrain() const
  1043. {
  1044. return town->faction->getNativeTerrain();
  1045. }
  1046. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1047. : count(_count)
  1048. {
  1049. MetaString formatter;
  1050. formatter.appendRawString(format);
  1051. formatter.replacePositiveNumber(count);
  1052. description = formatter.toString();
  1053. }
  1054. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1055. {
  1056. MetaString formatter;
  1057. formatter.appendRawString("%s %+d");
  1058. formatter.replaceRawString((*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated());
  1059. formatter.replacePositiveNumber(count);
  1060. description = formatter.toString();
  1061. }
  1062. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1063. count(_count),
  1064. description(std::move(fullDescription))
  1065. {
  1066. }
  1067. CTownAndVisitingHero::CTownAndVisitingHero()
  1068. {
  1069. setNodeType(TOWN_AND_VISITOR);
  1070. }
  1071. int GrowthInfo::totalGrowth() const
  1072. {
  1073. int ret = 0;
  1074. for(const Entry &entry : entries)
  1075. ret += entry.count;
  1076. return ret;
  1077. }
  1078. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1079. {
  1080. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1081. {
  1082. if (vstd::contains(dwelling.second, stack.type->getId())) //Dwelling with our creature
  1083. {
  1084. for(const auto & upgrID : dwelling.second)
  1085. {
  1086. if(vstd::contains(stack.type->upgrades, upgrID)) //possible upgrade
  1087. {
  1088. info.newID.push_back(upgrID);
  1089. info.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost());
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. VCMI_LIB_NAMESPACE_END