CGTownInstance.cpp 32 KB

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