CGTownInstance.cpp 32 KB

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