CGTownInstance.cpp 33 KB

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