CGTownInstance.cpp 33 KB

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