CGTownInstance.cpp 33 KB

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