CGTownInstance.cpp 33 KB

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