CGTownInstance.cpp 33 KB

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