CGTownInstance.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  414. {
  415. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  416. {
  417. std::vector<SlotID> nativeCrits; //slots
  418. for(const auto & elem : Slots())
  419. {
  420. if (elem.second->type->getFaction() == getFaction()) //native
  421. {
  422. nativeCrits.push_back(elem.first); //collect matching slots
  423. }
  424. }
  425. if(!nativeCrits.empty())
  426. {
  427. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  428. StackLocation sl(this, pos);
  429. const CCreature *c = getCreature(pos);
  430. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  431. {
  432. cb->changeStackCount(sl, c->getGrowth());
  433. }
  434. else //upgrade
  435. {
  436. cb->changeStackType(sl, c->upgrades.begin()->toCreature());
  437. }
  438. }
  439. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  440. {
  441. int i = rand.nextInt(std::min((int)town->creatures.size(), cb->getDate(Date::MONTH) << 1) - 1);
  442. if (!town->creatures[i].empty())
  443. {
  444. CreatureID c = town->creatures[i][0];
  445. SlotID n;
  446. TQuantity count = creatureGrowth(i);
  447. if (!count) // no dwelling
  448. count = VLC->creatures()->getById(c)->getGrowth();
  449. {//no lower tiers or above current month
  450. if ((n = getSlotFor(c)).validSlot())
  451. {
  452. StackLocation sl(this, n);
  453. if (slotEmpty(n))
  454. cb->insertNewStack(sl, c.toCreature(), count);
  455. else //add to existing
  456. cb->changeStackCount(sl, count);
  457. }
  458. }
  459. }
  460. }
  461. }
  462. }
  463. for(const auto & building : rewardableBuildings)
  464. building.second->newTurn(rand);
  465. if(hasBuilt(BuildingSubID::BANK) && bonusValue.second > 0)
  466. {
  467. TResources res;
  468. res[EGameResID::GOLD] = -500;
  469. cb->giveResources(getOwner(), res);
  470. cb->setObjPropertyValue(id, ObjProperty::BONUS_VALUE_SECOND, bonusValue.second - 500);
  471. }
  472. }
  473. /*
  474. int3 CGTownInstance::getSightCenter() const
  475. {
  476. return pos - int3(2,0,0);
  477. }
  478. */
  479. bool CGTownInstance::passableFor(PlayerColor color) const
  480. {
  481. if (!armedGarrison())//empty castle - anyone can visit
  482. return true;
  483. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  484. return false;
  485. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  486. }
  487. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  488. {
  489. offsets = {int3(-1,2,0), int3(+1,2,0)};
  490. }
  491. CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
  492. {
  493. if (!hasBuilt(BuildingID::SHIPYARD))
  494. return EGeneratorState::UNKNOWN;
  495. return IShipyard::shipyardStatus();
  496. }
  497. const IObjectInterface * CGTownInstance::getObject() const
  498. {
  499. return this;
  500. }
  501. void CGTownInstance::mergeGarrisonOnSiege() const
  502. {
  503. auto getWeakestStackSlot = [&](ui64 powerLimit)
  504. {
  505. std::vector<SlotID> weakSlots;
  506. auto stacksList = visitingHero->stacks;
  507. std::pair<SlotID, CStackInstance *> pair;
  508. while(!stacksList.empty())
  509. {
  510. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  511. if(powerLimit > pair.second->getPower() &&
  512. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  513. {
  514. weakSlots.push_back(pair.first);
  515. stacksList.erase(pair.first);
  516. }
  517. else
  518. break;
  519. }
  520. if(!weakSlots.empty())
  521. return *std::max_element(weakSlots.begin(), weakSlots.end());
  522. return SlotID();
  523. };
  524. auto count = static_cast<int>(stacks.size());
  525. for(int i = 0; i < count; i++)
  526. {
  527. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  528. {
  529. ui64 power = elem.second->getPower();
  530. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  531. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  532. power += visitingHero->getStack(dst).getPower();
  533. return power;
  534. });
  535. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  536. if(dst.validSlot())
  537. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  538. else
  539. {
  540. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  541. if(dst.validSlot())
  542. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  543. }
  544. }
  545. }
  546. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  547. {
  548. if (hasCapitol()) // search if there's an older capitol
  549. {
  550. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  551. for (const auto & town : state->getTowns())
  552. {
  553. if (town != this && town->hasCapitol())
  554. {
  555. RazeStructures rs;
  556. rs.tid = id;
  557. rs.bid.insert(BuildingID::CAPITOL);
  558. rs.destroyed = destroyed;
  559. cb->sendAndApply(&rs);
  560. return;
  561. }
  562. }
  563. }
  564. }
  565. void CGTownInstance::clearArmy() const
  566. {
  567. while(!stacks.empty())
  568. {
  569. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  570. }
  571. }
  572. BoatId CGTownInstance::getBoatType() const
  573. {
  574. return town->faction->boatType;
  575. }
  576. int CGTownInstance::getMarketEfficiency() const
  577. {
  578. if(!hasBuiltSomeTradeBuilding())
  579. return 0;
  580. const PlayerState *p = cb->getPlayerState(tempOwner);
  581. assert(p);
  582. int marketCount = 0;
  583. for(const CGTownInstance *t : p->getTowns())
  584. if(t->hasBuiltSomeTradeBuilding())
  585. marketCount++;
  586. return marketCount;
  587. }
  588. std::vector<TradeItemBuy> CGTownInstance::availableItemsIds(EMarketMode mode) const
  589. {
  590. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  591. {
  592. std::vector<TradeItemBuy> ret;
  593. for(const CArtifact *a : cb->gameState()->map->townMerchantArtifacts)
  594. if(a)
  595. ret.push_back(a->getId());
  596. else
  597. ret.push_back(ArtifactID{});
  598. return ret;
  599. }
  600. else if ( mode == EMarketMode::RESOURCE_SKILL )
  601. {
  602. return cb->gameState()->map->townUniversitySkills;
  603. }
  604. else
  605. return IMarket::availableItemsIds(mode);
  606. }
  607. ObjectInstanceID CGTownInstance::getObjInstanceID() const
  608. {
  609. return id;
  610. }
  611. void CGTownInstance::updateAppearance()
  612. {
  613. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  614. //FIXME: not the best way to do this
  615. auto app = getObjectHandler()->getOverride(terrain, this);
  616. if (app)
  617. appearance = app;
  618. }
  619. std::string CGTownInstance::nodeName() const
  620. {
  621. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + getNameTranslated();
  622. }
  623. void CGTownInstance::deserializationFix()
  624. {
  625. attachTo(townAndVis);
  626. //Hero is already handled by CGameState::attachArmedObjects
  627. // if(visitingHero)
  628. // visitingHero->attachTo(&townAndVis);
  629. // if(garrisonHero)
  630. // garrisonHero->attachTo(this);
  631. }
  632. void CGTownInstance::updateMoraleBonusFromArmy()
  633. {
  634. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  635. if(!b)
  636. {
  637. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
  638. addNewBonus(b);
  639. }
  640. if (garrisonHero)
  641. {
  642. b->val = 0;
  643. CBonusSystemNode::treeHasChanged();
  644. }
  645. else
  646. CArmedInstance::updateMoraleBonusFromArmy();
  647. }
  648. void CGTownInstance::recreateBuildingsBonuses()
  649. {
  650. BonusList bl;
  651. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  652. for(const auto & b : bl)
  653. removeBonus(b);
  654. for(const auto & bid : builtBuildings)
  655. {
  656. bool bonusesReplacedByUpgrade = false;
  657. for(const auto & upgradeID : builtBuildings)
  658. {
  659. const auto & upgrade = town->buildings.at(upgradeID);
  660. if (upgrade->getBase() == bid && upgrade->upgradeReplacesBonuses)
  661. bonusesReplacedByUpgrade = true;
  662. }
  663. // bonuses from this building are disabled and replaced by bonuses from an upgrade
  664. if (bonusesReplacedByUpgrade)
  665. continue;
  666. auto building = town->buildings.at(bid);
  667. if(building->buildingBonuses.empty())
  668. continue;
  669. for(auto & bonus : building->buildingBonuses)
  670. addNewBonus(bonus);
  671. }
  672. }
  673. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  674. {
  675. if(visitingHero.get() == h)
  676. return;
  677. if(h)
  678. {
  679. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  680. assert(p);
  681. h->detachFrom(*p);
  682. h->attachTo(townAndVis);
  683. visitingHero = h;
  684. h->visitedTown = this;
  685. h->inTownGarrison = false;
  686. }
  687. else
  688. {
  689. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  690. visitingHero->visitedTown = nullptr;
  691. visitingHero->detachFrom(townAndVis);
  692. visitingHero->attachTo(*p);
  693. visitingHero = nullptr;
  694. }
  695. }
  696. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  697. {
  698. if(garrisonHero.get() == h)
  699. return;
  700. if(h)
  701. {
  702. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  703. assert(p);
  704. h->detachFrom(*p);
  705. h->attachTo(*this);
  706. garrisonHero = h;
  707. h->visitedTown = this;
  708. h->inTownGarrison = true;
  709. }
  710. else
  711. {
  712. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  713. garrisonHero->visitedTown = nullptr;
  714. garrisonHero->inTownGarrison = false;
  715. garrisonHero->detachFrom(*this);
  716. garrisonHero->attachTo(*p);
  717. garrisonHero = nullptr;
  718. }
  719. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  720. }
  721. bool CGTownInstance::armedGarrison() const
  722. {
  723. return !stacks.empty() || garrisonHero;
  724. }
  725. const CTown * CGTownInstance::getTown() const
  726. {
  727. if(ID == Obj::RANDOM_TOWN)
  728. return VLC->townh->randomTown;
  729. else
  730. {
  731. if(nullptr == town)
  732. {
  733. return (*VLC->townh)[getFaction()]->town;
  734. }
  735. else
  736. return town;
  737. }
  738. }
  739. int CGTownInstance::getTownLevel() const
  740. {
  741. // count all buildings that are not upgrades
  742. int level = 0;
  743. for(const auto & bid : builtBuildings)
  744. {
  745. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  746. level++;
  747. }
  748. return level;
  749. }
  750. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  751. {
  752. return townAndVis;
  753. }
  754. std::string CGTownInstance::getNameTranslated() const
  755. {
  756. return VLC->generaltexth->translate(nameTextId);
  757. }
  758. std::string CGTownInstance::getNameTextID() const
  759. {
  760. return nameTextId;
  761. }
  762. void CGTownInstance::setNameTextId( const std::string & newName )
  763. {
  764. nameTextId = newName;
  765. }
  766. const CArmedInstance * CGTownInstance::getUpperArmy() const
  767. {
  768. if(garrisonHero)
  769. return garrisonHero;
  770. return this;
  771. }
  772. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  773. {
  774. return availableModes().empty() ? false : true;
  775. }
  776. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  777. {
  778. for(const auto & bid : builtBuildings)
  779. {
  780. if(town->buildings.at(bid)->subId == buildingID)
  781. return true;
  782. }
  783. return false;
  784. }
  785. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  786. {
  787. return vstd::contains(builtBuildings, buildingID);
  788. }
  789. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, FactionID townID) const
  790. {
  791. if (townID == town->faction->getId() || townID == FactionID::ANY)
  792. return hasBuilt(buildingID);
  793. return false;
  794. }
  795. void CGTownInstance::addBuilding(const BuildingID & buildingID)
  796. {
  797. if(buildingID == BuildingID::NONE)
  798. return;
  799. builtBuildings.insert(buildingID);
  800. }
  801. std::set<EMarketMode> CGTownInstance::availableModes() const
  802. {
  803. std::set<EMarketMode> result;
  804. for (const auto & buildingID : builtBuildings)
  805. {
  806. const auto * buildingPtr = town->buildings.at(buildingID).get();
  807. result.insert(buildingPtr->marketModes.begin(), buildingPtr->marketModes.end());
  808. }
  809. return result;
  810. }
  811. void CGTownInstance::removeBuilding(const BuildingID & buildingID)
  812. {
  813. if(!vstd::contains(builtBuildings, buildingID))
  814. return;
  815. builtBuildings.erase(buildingID);
  816. }
  817. void CGTownInstance::removeAllBuildings()
  818. {
  819. builtBuildings.clear();
  820. }
  821. std::set<BuildingID> CGTownInstance::getBuildings() const
  822. {
  823. return builtBuildings;
  824. }
  825. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  826. {
  827. if (vstd::contains(town->buildings, buildingID))
  828. return town->buildings.at(buildingID)->resources;
  829. else
  830. {
  831. logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), pos.toString(), buildingID.toEnum());
  832. return TResources();
  833. }
  834. }
  835. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  836. {
  837. const CBuilding * building = town->buildings.at(buildID);
  838. //TODO: find better solution to prevent infinite loops
  839. std::set<BuildingID> processed;
  840. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  841. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  842. {
  843. if (town->buildings.count(id) == 0)
  844. {
  845. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  846. return CBuilding::TRequired::OperatorAll();
  847. }
  848. const CBuilding * build = town->buildings.at(id);
  849. CBuilding::TRequired::OperatorAll requirements;
  850. if (!hasBuilt(id))
  851. {
  852. if (deep)
  853. requirements.expressions.emplace_back(id);
  854. else
  855. return id;
  856. }
  857. if(!vstd::contains(processed, id))
  858. {
  859. processed.insert(id);
  860. if (build->upgrade != BuildingID::NONE)
  861. requirements.expressions.push_back(dependTest(build->upgrade));
  862. requirements.expressions.push_back(build->requirements.morph(dependTest));
  863. }
  864. return requirements;
  865. };
  866. CBuilding::TRequired::OperatorAll requirements;
  867. if (building->upgrade != BuildingID::NONE)
  868. {
  869. const CBuilding * upgr = town->buildings.at(building->upgrade);
  870. requirements.expressions.push_back(dependTest(upgr->bid));
  871. processed.clear();
  872. }
  873. requirements.expressions.push_back(building->requirements.morph(dependTest));
  874. CBuilding::TRequired::Variant variant(requirements);
  875. CBuilding::TRequired ret(variant);
  876. ret.minimize();
  877. return ret;
  878. }
  879. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  880. {
  881. if(visitingHero == h)
  882. cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  883. else if(garrisonHero == h)
  884. cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  885. else
  886. {
  887. //should never ever happen
  888. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  889. throw std::runtime_error("unexpected hero in CGTownInstance::addHeroToStructureVisitors");
  890. }
  891. }
  892. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  893. {
  894. if(result.winner == BattleSide::ATTACKER)
  895. {
  896. clearArmy();
  897. onTownCaptured(hero->getOwner());
  898. }
  899. }
  900. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  901. {
  902. setOwner(winner);
  903. cb->changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  904. }
  905. void CGTownInstance::afterAddToMap(CMap * map)
  906. {
  907. map->towns.emplace_back(this);
  908. }
  909. void CGTownInstance::afterRemoveFromMap(CMap * map)
  910. {
  911. vstd::erase_if_present(map->towns, this);
  912. }
  913. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  914. {
  915. CGObjectInstance::serializeJsonOwner(handler);
  916. if(!handler.saving)
  917. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  918. CArmedInstance::serializeJsonOptions(handler);
  919. handler.serializeString("name", nameTextId);
  920. {
  921. auto decodeBuilding = [this](const std::string & identifier) -> si32
  922. {
  923. auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  924. if(rawId)
  925. return rawId.value();
  926. else
  927. return -1;
  928. };
  929. auto encodeBuilding = [this](si32 index) -> std::string
  930. {
  931. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  932. };
  933. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  934. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  935. if(handler.saving)
  936. {
  937. bool customBuildings = false;
  938. boost::logic::tribool hasFort(false);
  939. for(const BuildingID & id : forbiddenBuildings)
  940. {
  941. buildingsLIC.none.insert(id.getNum());
  942. customBuildings = true;
  943. }
  944. for(const BuildingID & id : builtBuildings)
  945. {
  946. if(id == BuildingID::DEFAULT)
  947. continue;
  948. const CBuilding * building = getTown()->buildings.at(id);
  949. if(building->mode == CBuilding::BUILD_AUTO)
  950. continue;
  951. if(id == BuildingID::FORT)
  952. hasFort = true;
  953. buildingsLIC.all.insert(id.getNum());
  954. customBuildings = true;
  955. }
  956. if(customBuildings)
  957. handler.serializeLIC("buildings", buildingsLIC);
  958. else
  959. handler.serializeBool("hasFort",hasFort);
  960. }
  961. else
  962. {
  963. handler.serializeLIC("buildings", buildingsLIC);
  964. addBuilding(BuildingID::VILLAGE_HALL);
  965. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  966. {
  967. addBuilding(BuildingID::DEFAULT);
  968. bool hasFort = false;
  969. handler.serializeBool("hasFort",hasFort);
  970. if(hasFort)
  971. addBuilding(BuildingID::FORT);
  972. }
  973. else
  974. {
  975. for(const si32 item : buildingsLIC.none)
  976. forbiddenBuildings.insert(BuildingID(item));
  977. for(const si32 item : buildingsLIC.all)
  978. addBuilding(BuildingID(item));
  979. }
  980. }
  981. }
  982. {
  983. handler.serializeIdArray( "possibleSpells", possibleSpells);
  984. handler.serializeIdArray( "obligatorySpells", obligatorySpells);
  985. }
  986. {
  987. auto eventsHandler = handler.enterArray("events");
  988. eventsHandler.syncSize(events, JsonNode::JsonType::DATA_VECTOR);
  989. eventsHandler.serializeStruct(events);
  990. }
  991. }
  992. FactionID CGTownInstance::getFaction() const
  993. {
  994. return FactionID(subID.getNum());
  995. }
  996. TerrainId CGTownInstance::getNativeTerrain() const
  997. {
  998. return town->faction->getNativeTerrain();
  999. }
  1000. ArtifactID CGTownInstance::getWarMachineInBuilding(BuildingID building) const
  1001. {
  1002. if (builtBuildings.count(building) == 0)
  1003. return ArtifactID::NONE;
  1004. if (building == BuildingID::BLACKSMITH && town->warMachineDeprecated.hasValue())
  1005. return town->warMachineDeprecated.toCreature()->warMachine;
  1006. return town->buildings.at(building)->warMachine;
  1007. }
  1008. bool CGTownInstance::isWarMachineAvailable(ArtifactID warMachine) const
  1009. {
  1010. for (auto const & buildingID : builtBuildings)
  1011. if (town->buildings.at(buildingID)->warMachine == warMachine)
  1012. return true;
  1013. if (builtBuildings.count(BuildingID::BLACKSMITH) &&
  1014. town->warMachineDeprecated.hasValue() &&
  1015. town->warMachineDeprecated.toCreature()->warMachine == warMachine)
  1016. return true;
  1017. return false;
  1018. }
  1019. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1020. : count(_count)
  1021. {
  1022. MetaString formatter;
  1023. formatter.appendRawString(format);
  1024. formatter.replacePositiveNumber(count);
  1025. description = formatter.toString();
  1026. }
  1027. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1028. {
  1029. MetaString formatter;
  1030. formatter.appendRawString("%s %+d");
  1031. formatter.replaceRawString((*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated());
  1032. formatter.replacePositiveNumber(count);
  1033. description = formatter.toString();
  1034. }
  1035. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1036. count(_count),
  1037. description(std::move(fullDescription))
  1038. {
  1039. }
  1040. CTownAndVisitingHero::CTownAndVisitingHero()
  1041. {
  1042. setNodeType(TOWN_AND_VISITOR);
  1043. }
  1044. int GrowthInfo::totalGrowth() const
  1045. {
  1046. int ret = 0;
  1047. for(const Entry &entry : entries)
  1048. ret += entry.count;
  1049. // always round up income - we don't want buildings to always produce zero if handicap in use
  1050. return vstd::divideAndCeil(ret * handicapPercentage, 100);
  1051. }
  1052. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1053. {
  1054. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1055. {
  1056. if (vstd::contains(dwelling.second, stack.type->getId())) //Dwelling with our creature
  1057. {
  1058. for(const auto & upgrID : dwelling.second)
  1059. {
  1060. if(vstd::contains(stack.type->upgrades, upgrID)) //possible upgrade
  1061. {
  1062. info.newID.push_back(upgrID);
  1063. info.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost());
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. void CGTownInstance::postDeserialize()
  1070. {
  1071. setNodeType(CBonusSystemNode::TOWN);
  1072. for(auto & building : rewardableBuildings)
  1073. building.second->town = this;
  1074. }
  1075. std::map<BuildingID, TownRewardableBuildingInstance*> CGTownInstance::convertOldBuildings(std::vector<TownRewardableBuildingInstance*> oldVector)
  1076. {
  1077. std::map<BuildingID, TownRewardableBuildingInstance*> result;
  1078. for(auto & building : oldVector)
  1079. {
  1080. result[building->getBuildingType()] = new TownRewardableBuildingInstance(*building);
  1081. delete building;
  1082. }
  1083. return result;
  1084. }
  1085. VCMI_LIB_NAMESPACE_END