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