CGTownInstance.cpp 33 KB

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