CGTownInstance.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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 "CObjectClassesHandler.h"
  14. #include "../spells/CSpellHandler.h"
  15. #include "../bonuses/Bonus.h"
  16. #include "../battle/IBattleInfoCallback.h"
  17. #include "../NetPacks.h"
  18. #include "../CConfigHandler.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../CModHandler.h"
  21. #include "../IGameCallback.h"
  22. #include "../CGameState.h"
  23. #include "../mapping/CMap.h"
  24. #include "../CPlayerState.h"
  25. #include "../TerrainHandler.h"
  26. #include "../serializer/JsonSerializeFormat.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  29. std::vector<int> CGTownInstance::universitySkills;
  30. int CGTownInstance::getSightRadius() const //returns sight distance
  31. {
  32. auto ret = CBuilding::HEIGHT_NO_TOWER;
  33. for(const auto & bid : builtBuildings)
  34. {
  35. if(bid.IsSpecialOrGrail())
  36. {
  37. auto height = town->buildings.at(bid)->height;
  38. if(ret < height)
  39. ret = height;
  40. }
  41. }
  42. return ret;
  43. }
  44. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  45. {
  46. ///this is freakin' overcomplicated solution
  47. switch (what)
  48. {
  49. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  50. bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, visitingHero->id.getNum());
  51. break;
  52. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  53. bonusingBuildings[val]->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  54. break;
  55. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  56. bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, garrisonHero->id.getNum());
  57. break;
  58. case ObjProperty::BONUS_VALUE_FIRST:
  59. bonusValue.first = val;
  60. break;
  61. case ObjProperty::BONUS_VALUE_SECOND:
  62. bonusValue.second = val;
  63. break;
  64. case ObjProperty::REWARD_RANDOMIZE:
  65. bonusingBuildings[val]->setProperty(ObjProperty::REWARD_RANDOMIZE, 0);
  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 >=GameConstants::CREATURES_PER_TOWN)
  117. return ret;
  118. if (creatures[level].second.empty())
  119. return ret; //no dwelling
  120. const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
  121. const int base = creature->getGrowth();
  122. int castleBonus = 0;
  123. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  124. if (hasBuilt(BuildingID::CASTLE))
  125. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  126. else if (hasBuilt(BuildingID::CITADEL))
  127. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  128. if(town->hordeLvl.at(0) == level)//horde 1
  129. if(hasBuilt(BuildingID::HORDE_1))
  130. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  131. if(town->hordeLvl.at(1) == level)//horde 2
  132. if(hasBuilt(BuildingID::HORDE_2))
  133. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  134. //statue-of-legion-like bonus: % to base+castle
  135. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(BonusType::CREATURE_GROWTH_PERCENT));
  136. for(const auto & b : *bonuses2)
  137. {
  138. const auto growth = b->val * (base + castleBonus) / 100;
  139. ret.entries.emplace_back(growth, b->Description(growth));
  140. }
  141. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  142. TConstBonusListPtr bonuses = getBonuses(Selector::type()(BonusType::CREATURE_GROWTH).And(Selector::subtype()(level)));
  143. for(const auto & b : *bonuses)
  144. ret.entries.emplace_back(b->val, b->Description());
  145. int dwellingBonus = 0;
  146. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  147. {
  148. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  149. }
  150. if(dwellingBonus)
  151. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  152. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  153. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  154. return ret;
  155. }
  156. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  157. {
  158. int totalBonus = 0;
  159. for (const auto& dwelling : dwellings)
  160. {
  161. for (const auto& creature : dwelling->creatures)
  162. {
  163. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  164. }
  165. }
  166. return totalBonus;
  167. }
  168. TResources CGTownInstance::dailyIncome() const
  169. {
  170. TResources ret;
  171. for(const auto & p : town->buildings)
  172. {
  173. BuildingID buildingUpgrade;
  174. for(const auto & p2 : town->buildings)
  175. {
  176. if (p2.second->upgrade == p.first)
  177. {
  178. buildingUpgrade = p2.first;
  179. }
  180. }
  181. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  182. {
  183. ret += p.second->produce;
  184. }
  185. }
  186. return ret;
  187. }
  188. bool CGTownInstance::hasFort() const
  189. {
  190. return hasBuilt(BuildingID::FORT);
  191. }
  192. bool CGTownInstance::hasCapitol() const
  193. {
  194. return hasBuilt(BuildingID::CAPITOL);
  195. }
  196. CGTownInstance::CGTownInstance():
  197. IShipyard(this),
  198. IMarket(),
  199. town(nullptr),
  200. builded(0),
  201. destroyed(0),
  202. identifier(0),
  203. alignmentToPlayer(PlayerColor::NEUTRAL)
  204. {
  205. this->setNodeType(CBonusSystemNode::TOWN);
  206. }
  207. CGTownInstance::~CGTownInstance()
  208. {
  209. for (auto & elem : bonusingBuildings)
  210. delete elem;
  211. }
  212. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  213. {
  214. if(checkGuild && mageGuildLevel() < level)
  215. return 0;
  216. int ret = 6 - level; //how many spells are available at this level
  217. if (hasBuilt(BuildingSubID::LIBRARY))
  218. ret++;
  219. return ret;
  220. }
  221. bool CGTownInstance::needsLastStack() const
  222. {
  223. return garrisonHero != nullptr;
  224. }
  225. void CGTownInstance::setOwner(const PlayerColor & player) const
  226. {
  227. removeCapitols(player);
  228. cb->setOwner(this, player);
  229. }
  230. void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  231. {
  232. for (auto building : bonusingBuildings)
  233. building->blockingDialogAnswered(hero, answer);
  234. }
  235. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  236. {
  237. if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  238. {
  239. if(armedGarrison() || visitingHero)
  240. {
  241. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  242. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  243. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  244. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  245. {
  246. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  247. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  248. if(nodeSiege == (CBonusSystemNode *)this)
  249. cb->swapGarrisonOnSiege(this->id);
  250. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  251. }
  252. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  253. }
  254. else
  255. {
  256. auto heroColor = h->getOwner();
  257. onTownCaptured(heroColor);
  258. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  259. {
  260. return; //we just won game, we do not need to perform any extra actions
  261. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  262. }
  263. cb->heroVisitCastle(this, h);
  264. }
  265. }
  266. else if(h->visitablePos() == visitablePos())
  267. {
  268. bool commander_recover = h->commander && !h->commander->alive;
  269. if (commander_recover) // rise commander from dead
  270. {
  271. SetCommanderProperty scp;
  272. scp.heroid = h->id;
  273. scp.which = SetCommanderProperty::ALIVE;
  274. scp.amount = 1;
  275. cb->sendAndApply(&scp);
  276. }
  277. cb->heroVisitCastle(this, h);
  278. // TODO(vmarkovtsev): implement payment for rising the commander
  279. if (commander_recover) // info window about commander
  280. {
  281. InfoWindow iw;
  282. iw.player = h->tempOwner;
  283. iw.text << h->commander->getName();
  284. iw.components.emplace_back(*h->commander);
  285. cb->showInfoDialog(&iw);
  286. }
  287. }
  288. else
  289. {
  290. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), name);
  291. }
  292. }
  293. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  294. {
  295. //FIXME: find out why this issue appears on random maps
  296. if(visitingHero == h)
  297. {
  298. cb->stopHeroVisitCastle(this, h);
  299. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), name);
  300. }
  301. else
  302. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), name);
  303. }
  304. std::string CGTownInstance::getObjectName() const
  305. {
  306. return name + ", " + town->faction->getNameTranslated();
  307. }
  308. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  309. {
  310. return town->getBuildingType(subId) != BuildingID::NONE;
  311. }
  312. void CGTownInstance::initOverriddenBids()
  313. {
  314. for(const auto & bid : builtBuildings)
  315. {
  316. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  317. for(const auto & overrideIt : overrideThem)
  318. overriddenBuildings.insert(overrideIt);
  319. }
  320. }
  321. bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
  322. {
  323. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  324. {
  325. return building->getBuildingType().num == bid;
  326. });
  327. return present != bonusingBuildings.end();
  328. }
  329. void CGTownInstance::addTownBonuses(CRandomGenerator & rand)
  330. {
  331. for(const auto & kvp : town->buildings)
  332. {
  333. if(vstd::contains(overriddenBuildings, kvp.first))
  334. continue;
  335. if(kvp.second->IsVisitingBonus())
  336. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  337. if(kvp.second->IsWeekBonus())
  338. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  339. if(kvp.second->subId == BuildingSubID::CUSTOM_VISITING_REWARD)
  340. bonusingBuildings.push_back(new CTownRewardableBuilding(kvp.second->bid, kvp.second->subId, this, 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::EBuildingID 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. auto building = town->buildings.at(bid);
  386. auto isVisitingBonus = building->IsVisitingBonus();
  387. auto isWeekBonus = building->IsWeekBonus();
  388. if(!isVisitingBonus && !isWeekBonus)
  389. return;
  390. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  391. delete freeIt;
  392. }
  393. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  394. {
  395. blockVisit = true;
  396. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  397. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  398. else
  399. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  400. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  401. {
  402. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  403. int upgradeNum = 0;
  404. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  405. {
  406. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  407. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  408. }
  409. }
  410. initOverriddenBids();
  411. addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector.
  412. recreateBuildingsBonuses();
  413. updateAppearance();
  414. }
  415. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  416. {
  417. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  418. {
  419. //give resources if there's a Mystic Pond
  420. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  421. && cb->getDate(Date::DAY) != 1
  422. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  423. )
  424. {
  425. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  426. resID = (resID==2)?1:resID;
  427. int resVal = rand.nextInt(1, 4);//with size 1..4
  428. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  429. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  430. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  431. }
  432. for(const auto * manaVortex : getBonusingBuildings(BuildingSubID::MANA_VORTEX))
  433. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  434. //get Mana Vortex or Stables bonuses
  435. //same code is in the CGameHandler::buildStructure method
  436. if (visitingHero != nullptr)
  437. cb->visitCastleObjects(this, visitingHero);
  438. if (garrisonHero != nullptr)
  439. cb->visitCastleObjects(this, garrisonHero);
  440. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  441. {
  442. std::vector<SlotID> nativeCrits; //slots
  443. for(const auto & elem : Slots())
  444. {
  445. if (elem.second->type->getFaction() == subID) //native
  446. {
  447. nativeCrits.push_back(elem.first); //collect matching slots
  448. }
  449. }
  450. if(!nativeCrits.empty())
  451. {
  452. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  453. StackLocation sl(this, pos);
  454. const CCreature *c = getCreature(pos);
  455. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  456. {
  457. cb->changeStackCount(sl, c->getGrowth());
  458. }
  459. else //upgrade
  460. {
  461. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  462. }
  463. }
  464. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  465. {
  466. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  467. if (!town->creatures[i].empty())
  468. {
  469. CreatureID c = town->creatures[i][0];
  470. SlotID n;
  471. TQuantity count = creatureGrowth(i);
  472. if (!count) // no dwelling
  473. count = VLC->creatures()->getByIndex(c)->getGrowth();
  474. {//no lower tiers or above current month
  475. if ((n = getSlotFor(c)).validSlot())
  476. {
  477. StackLocation sl(this, n);
  478. if (slotEmpty(n))
  479. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  480. else //add to existing
  481. cb->changeStackCount(sl, count);
  482. }
  483. }
  484. }
  485. }
  486. }
  487. }
  488. for(const auto * rewardableBuilding : getBonusingBuildings(BuildingSubID::CUSTOM_VISITING_REWARD))
  489. rewardableBuilding->newTurn(rand);
  490. }
  491. /*
  492. int3 CGTownInstance::getSightCenter() const
  493. {
  494. return pos - int3(2,0,0);
  495. }
  496. */
  497. bool CGTownInstance::passableFor(PlayerColor color) const
  498. {
  499. if (!armedGarrison())//empty castle - anyone can visit
  500. return true;
  501. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  502. return false;
  503. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  504. }
  505. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  506. {
  507. offsets = {int3(-1,2,0), int3(-3,2,0)};
  508. }
  509. void CGTownInstance::mergeGarrisonOnSiege() const
  510. {
  511. auto getWeakestStackSlot = [&](ui64 powerLimit)
  512. {
  513. std::vector<SlotID> weakSlots;
  514. auto stacksList = visitingHero->stacks;
  515. std::pair<SlotID, CStackInstance *> pair;
  516. while(!stacksList.empty())
  517. {
  518. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  519. if(powerLimit > pair.second->getPower() &&
  520. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  521. {
  522. weakSlots.push_back(pair.first);
  523. stacksList.erase(pair.first);
  524. }
  525. else
  526. break;
  527. }
  528. if(!weakSlots.empty())
  529. return *std::max_element(weakSlots.begin(), weakSlots.end());
  530. return SlotID();
  531. };
  532. auto count = static_cast<int>(stacks.size());
  533. for(int i = 0; i < count; i++)
  534. {
  535. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  536. {
  537. ui64 power = elem.second->getPower();
  538. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  539. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  540. power += visitingHero->getStack(dst).getPower();
  541. return power;
  542. });
  543. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  544. if(dst.validSlot())
  545. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  546. else
  547. {
  548. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  549. if(dst.validSlot())
  550. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  551. }
  552. }
  553. }
  554. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  555. {
  556. if (hasCapitol()) // search if there's an older capitol
  557. {
  558. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  559. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  560. {
  561. if (*i != this && (*i)->hasCapitol())
  562. {
  563. RazeStructures rs;
  564. rs.tid = id;
  565. rs.bid.insert(BuildingID::CAPITOL);
  566. rs.destroyed = destroyed;
  567. cb->sendAndApply(&rs);
  568. return;
  569. }
  570. }
  571. }
  572. }
  573. void CGTownInstance::clearArmy() const
  574. {
  575. while(!stacks.empty())
  576. {
  577. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  578. }
  579. }
  580. BoatId CGTownInstance::getBoatType() const
  581. {
  582. switch (town->faction->alignment)
  583. {
  584. case EAlignment::EVIL : return EBoatId::BOAT_EVIL;
  585. case EAlignment::GOOD : return EBoatId::BOAT_GOOD;
  586. case EAlignment::NEUTRAL : return EBoatId::BOAT_NEUTRAL;
  587. default: return EBoatId::NONE;
  588. }
  589. }
  590. int CGTownInstance::getMarketEfficiency() const
  591. {
  592. if(!hasBuiltSomeTradeBuilding())
  593. return 0;
  594. const PlayerState *p = cb->getPlayerState(tempOwner);
  595. assert(p);
  596. int marketCount = 0;
  597. for(const CGTownInstance *t : p->towns)
  598. if(t->hasBuiltSomeTradeBuilding())
  599. marketCount++;
  600. return marketCount;
  601. }
  602. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  603. {
  604. switch(mode)
  605. {
  606. case EMarketMode::RESOURCE_RESOURCE:
  607. case EMarketMode::RESOURCE_PLAYER:
  608. return hasBuilt(BuildingID::MARKETPLACE);
  609. case EMarketMode::ARTIFACT_RESOURCE:
  610. case EMarketMode::RESOURCE_ARTIFACT:
  611. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  612. case EMarketMode::CREATURE_RESOURCE:
  613. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  614. case EMarketMode::CREATURE_UNDEAD:
  615. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  616. case EMarketMode::RESOURCE_SKILL:
  617. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  618. default:
  619. assert(0);
  620. return false;
  621. }
  622. }
  623. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  624. {
  625. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  626. {
  627. std::vector<int> ret;
  628. for(const CArtifact *a : merchantArtifacts)
  629. if(a)
  630. ret.push_back(a->getId());
  631. else
  632. ret.push_back(-1);
  633. return ret;
  634. }
  635. else if ( mode == EMarketMode::RESOURCE_SKILL )
  636. {
  637. return universitySkills;
  638. }
  639. else
  640. return IMarket::availableItemsIds(mode);
  641. }
  642. void CGTownInstance::setType(si32 ID, si32 subID)
  643. {
  644. assert(ID == Obj::TOWN); // just in case
  645. CGObjectInstance::setType(ID, subID);
  646. town = (*VLC->townh)[subID]->town;
  647. randomizeArmy(subID);
  648. updateAppearance();
  649. }
  650. void CGTownInstance::updateAppearance()
  651. {
  652. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  653. //FIXME: not the best way to do this
  654. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  655. if (app)
  656. appearance = app;
  657. }
  658. std::string CGTownInstance::nodeName() const
  659. {
  660. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  661. }
  662. void CGTownInstance::deserializationFix()
  663. {
  664. attachTo(townAndVis);
  665. //Hero is already handled by CGameState::attachArmedObjects
  666. // if(visitingHero)
  667. // visitingHero->attachTo(&townAndVis);
  668. // if(garrisonHero)
  669. // garrisonHero->attachTo(this);
  670. }
  671. void CGTownInstance::updateMoraleBonusFromArmy()
  672. {
  673. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  674. if(!b)
  675. {
  676. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, -1);
  677. addNewBonus(b);
  678. }
  679. if (garrisonHero)
  680. {
  681. b->val = 0;
  682. CBonusSystemNode::treeHasChanged();
  683. }
  684. else
  685. CArmedInstance::updateMoraleBonusFromArmy();
  686. }
  687. void CGTownInstance::recreateBuildingsBonuses()
  688. {
  689. BonusList bl;
  690. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  691. for(const auto & b : bl)
  692. removeBonus(b);
  693. for(const auto & bid : builtBuildings)
  694. {
  695. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  696. continue;
  697. auto building = town->buildings.at(bid);
  698. if(building->buildingBonuses.empty())
  699. continue;
  700. for(auto & bonus : building->buildingBonuses)
  701. addNewBonus(bonus);
  702. }
  703. }
  704. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  705. {
  706. if(visitingHero.get() == h)
  707. return;
  708. if(h)
  709. {
  710. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  711. assert(p);
  712. h->detachFrom(*p);
  713. h->attachTo(townAndVis);
  714. visitingHero = h;
  715. h->visitedTown = this;
  716. h->inTownGarrison = false;
  717. }
  718. else
  719. {
  720. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  721. visitingHero->visitedTown = nullptr;
  722. visitingHero->detachFrom(townAndVis);
  723. visitingHero->attachTo(*p);
  724. visitingHero = nullptr;
  725. }
  726. }
  727. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  728. {
  729. if(garrisonHero.get() == h)
  730. return;
  731. if(h)
  732. {
  733. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  734. assert(p);
  735. h->detachFrom(*p);
  736. h->attachTo(*this);
  737. garrisonHero = h;
  738. h->visitedTown = this;
  739. h->inTownGarrison = true;
  740. }
  741. else
  742. {
  743. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  744. garrisonHero->visitedTown = nullptr;
  745. garrisonHero->inTownGarrison = false;
  746. garrisonHero->detachFrom(*this);
  747. garrisonHero->attachTo(*p);
  748. garrisonHero = nullptr;
  749. }
  750. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  751. }
  752. bool CGTownInstance::armedGarrison() const
  753. {
  754. return !stacks.empty() || garrisonHero;
  755. }
  756. const CTown * CGTownInstance::getTown() const
  757. {
  758. if(ID == Obj::RANDOM_TOWN)
  759. return VLC->townh->randomTown;
  760. else
  761. {
  762. if(nullptr == town)
  763. {
  764. return (*VLC->townh)[subID]->town;
  765. }
  766. else
  767. return town;
  768. }
  769. }
  770. int CGTownInstance::getTownLevel() const
  771. {
  772. // count all buildings that are not upgrades
  773. int level = 0;
  774. for(const auto & bid : builtBuildings)
  775. {
  776. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  777. level++;
  778. }
  779. return level;
  780. }
  781. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  782. {
  783. return townAndVis;
  784. }
  785. std::string CGTownInstance::getNameTranslated() const
  786. {
  787. return name;
  788. }
  789. void CGTownInstance::setNameTranslated( const std::string & newName )
  790. {
  791. name = newName;
  792. }
  793. const CArmedInstance * CGTownInstance::getUpperArmy() const
  794. {
  795. if(garrisonHero)
  796. return garrisonHero;
  797. return this;
  798. }
  799. std::vector<const CGTownBuilding *> CGTownInstance::getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const
  800. {
  801. std::vector<const CGTownBuilding *> ret;
  802. for(auto * const building : bonusingBuildings)
  803. {
  804. if(building->getBuildingSubtype() == subId)
  805. ret.push_back(building);
  806. }
  807. return ret;
  808. }
  809. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  810. {
  811. for(const auto & bid : builtBuildings)
  812. {
  813. if(town->buildings.at(bid)->IsTradeBuilding())
  814. return true;
  815. }
  816. return false;
  817. }
  818. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  819. {
  820. for(const auto & bid : builtBuildings)
  821. {
  822. if(town->buildings.at(bid)->subId == buildingID)
  823. return true;
  824. }
  825. return false;
  826. }
  827. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  828. {
  829. return vstd::contains(builtBuildings, buildingID);
  830. }
  831. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  832. {
  833. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  834. return hasBuilt(buildingID);
  835. return false;
  836. }
  837. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  838. {
  839. if (vstd::contains(town->buildings, buildingID))
  840. return town->buildings.at(buildingID)->resources;
  841. else
  842. {
  843. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  844. return TResources();
  845. }
  846. }
  847. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  848. {
  849. const CBuilding * building = town->buildings.at(buildID);
  850. //TODO: find better solution to prevent infinite loops
  851. std::set<BuildingID> processed;
  852. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  853. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  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->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  890. else if(garrisonHero == h)
  891. cb->setObjProperty(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("internal error");
  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. FoWChange fw;
  911. fw.player = winner;
  912. fw.mode = 1;
  913. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  914. cb->sendAndApply(& fw);
  915. }
  916. void CGTownInstance::afterAddToMap(CMap * map)
  917. {
  918. if(ID == Obj::TOWN)
  919. map->towns.emplace_back(this);
  920. }
  921. void CGTownInstance::afterRemoveFromMap(CMap * map)
  922. {
  923. if (ID == Obj::TOWN)
  924. vstd::erase_if_present(map->towns, this);
  925. }
  926. void CGTownInstance::reset()
  927. {
  928. CGTownInstance::merchantArtifacts.clear();
  929. CGTownInstance::universitySkills.clear();
  930. }
  931. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  932. {
  933. static const std::vector<std::string> FORMATIONS = { "wide", "tight" };
  934. CGObjectInstance::serializeJsonOwner(handler);
  935. CCreatureSet::serializeJson(handler, "army", 7);
  936. handler.serializeEnum("tightFormation", formation, FORMATIONS);
  937. handler.serializeString("name", name);
  938. {
  939. auto decodeBuilding = [this](const std::string & identifier) -> si32
  940. {
  941. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  942. if(rawId)
  943. return rawId.value();
  944. else
  945. return -1;
  946. };
  947. auto encodeBuilding = [this](si32 index) -> std::string
  948. {
  949. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  950. };
  951. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  952. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  953. if(handler.saving)
  954. {
  955. bool customBuildings = false;
  956. boost::logic::tribool hasFort(false);
  957. for(const BuildingID & id : forbiddenBuildings)
  958. {
  959. buildingsLIC.none.insert(id);
  960. customBuildings = true;
  961. }
  962. for(const BuildingID & id : builtBuildings)
  963. {
  964. if(id == BuildingID::DEFAULT)
  965. continue;
  966. const CBuilding * building = getTown()->buildings.at(id);
  967. if(building->mode == CBuilding::BUILD_AUTO)
  968. continue;
  969. if(id == BuildingID::FORT)
  970. hasFort = true;
  971. buildingsLIC.all.insert(id);
  972. customBuildings = true;
  973. }
  974. if(customBuildings)
  975. handler.serializeLIC("buildings", buildingsLIC);
  976. else
  977. handler.serializeBool("hasFort",hasFort);
  978. }
  979. else
  980. {
  981. handler.serializeLIC("buildings", buildingsLIC);
  982. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  983. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  984. {
  985. builtBuildings.insert(BuildingID::DEFAULT);
  986. bool hasFort = false;
  987. handler.serializeBool("hasFort",hasFort);
  988. if(hasFort)
  989. builtBuildings.insert(BuildingID::FORT);
  990. }
  991. else
  992. {
  993. for(const si32 item : buildingsLIC.none)
  994. forbiddenBuildings.insert(BuildingID(item));
  995. for(const si32 item : buildingsLIC.all)
  996. builtBuildings.insert(BuildingID(item));
  997. }
  998. }
  999. }
  1000. {
  1001. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1002. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1003. if(handler.saving)
  1004. {
  1005. for(const SpellID & id : possibleSpells)
  1006. spellsLIC.any[id.num] = true;
  1007. for(const SpellID & id : obligatorySpells)
  1008. spellsLIC.all[id.num] = true;
  1009. }
  1010. handler.serializeLIC("spells", spellsLIC);
  1011. if(!handler.saving)
  1012. {
  1013. possibleSpells.clear();
  1014. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1015. {
  1016. if(spellsLIC.any[idx])
  1017. possibleSpells.emplace_back(idx);
  1018. }
  1019. obligatorySpells.clear();
  1020. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1021. {
  1022. if(spellsLIC.all[idx])
  1023. obligatorySpells.emplace_back(idx);
  1024. }
  1025. }
  1026. }
  1027. }
  1028. FactionID CGTownInstance::getFaction() const
  1029. {
  1030. return town->faction->getId();
  1031. }
  1032. TerrainId CGTownInstance::getNativeTerrain() const
  1033. {
  1034. return town->faction->getNativeTerrain();
  1035. }
  1036. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1037. : count(_count)
  1038. {
  1039. description = boost::str(boost::format(format) % count);
  1040. }
  1041. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1042. {
  1043. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1044. }
  1045. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1046. count(_count),
  1047. description(std::move(fullDescription))
  1048. {
  1049. }
  1050. CTownAndVisitingHero::CTownAndVisitingHero()
  1051. {
  1052. setNodeType(TOWN_AND_VISITOR);
  1053. }
  1054. int GrowthInfo::totalGrowth() const
  1055. {
  1056. int ret = 0;
  1057. for(const Entry &entry : entries)
  1058. ret += entry.count;
  1059. return ret;
  1060. }
  1061. VCMI_LIB_NAMESPACE_END