CGTownInstance.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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 "../NetPacks.h"
  17. #include "../CConfigHandler.h"
  18. #include "../CGeneralTextHandler.h"
  19. #include "../IGameCallback.h"
  20. #include "../gameState/CGameState.h"
  21. #include "../mapping/CMap.h"
  22. #include "../CPlayerState.h"
  23. #include "../TerrainHandler.h"
  24. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  26. #include "../modding/ModScope.h"
  27. #include "../serializer/JsonSerializeFormat.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  30. std::vector<int> CGTownInstance::universitySkills;
  31. int CGTownInstance::getSightRadius() const //returns sight distance
  32. {
  33. auto ret = CBuilding::HEIGHT_NO_TOWER;
  34. for(const auto & bid : builtBuildings)
  35. {
  36. if(bid.IsSpecialOrGrail())
  37. {
  38. auto height = town->buildings.at(bid)->height;
  39. if(ret < height)
  40. ret = height;
  41. }
  42. }
  43. return ret;
  44. }
  45. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  46. {
  47. ///this is freakin' overcomplicated solution
  48. switch (what)
  49. {
  50. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  51. bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, visitingHero->id.getNum());
  52. break;
  53. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  54. bonusingBuildings[val]->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  55. break;
  56. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  57. bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, garrisonHero->id.getNum());
  58. break;
  59. case ObjProperty::BONUS_VALUE_FIRST:
  60. bonusValue.first = val;
  61. break;
  62. case ObjProperty::BONUS_VALUE_SECOND:
  63. bonusValue.second = val;
  64. break;
  65. case ObjProperty::REWARD_RANDOMIZE:
  66. bonusingBuildings[val]->setProperty(ObjProperty::REWARD_RANDOMIZE, 0);
  67. break;
  68. }
  69. }
  70. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  71. {
  72. if (hasBuilt(BuildingID::CASTLE))
  73. return CASTLE;
  74. if (hasBuilt(BuildingID::CITADEL))
  75. return CITADEL;
  76. if (hasBuilt(BuildingID::FORT))
  77. return FORT;
  78. return NONE;
  79. }
  80. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  81. {
  82. if (hasBuilt(BuildingID::CAPITOL))
  83. return 3;
  84. if (hasBuilt(BuildingID::CITY_HALL))
  85. return 2;
  86. if (hasBuilt(BuildingID::TOWN_HALL))
  87. return 1;
  88. if (hasBuilt(BuildingID::VILLAGE_HALL))
  89. return 0;
  90. return -1;
  91. }
  92. int CGTownInstance::mageGuildLevel() const
  93. {
  94. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  95. return 5;
  96. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  97. return 4;
  98. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  99. return 3;
  100. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  101. return 2;
  102. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  103. return 1;
  104. return 0;
  105. }
  106. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  107. {
  108. return town->hordeLvl.at(HID);
  109. }
  110. int CGTownInstance::creatureGrowth(const int & level) const
  111. {
  112. return getGrowthInfo(level).totalGrowth();
  113. }
  114. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  115. {
  116. GrowthInfo ret;
  117. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  118. return ret;
  119. if (creatures[level].second.empty())
  120. return ret; //no dwelling
  121. const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
  122. const int base = creature->getGrowth();
  123. int castleBonus = 0;
  124. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  125. if (hasBuilt(BuildingID::CASTLE))
  126. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  127. else if (hasBuilt(BuildingID::CITADEL))
  128. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  129. if(town->hordeLvl.at(0) == level)//horde 1
  130. if(hasBuilt(BuildingID::HORDE_1))
  131. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  132. if(town->hordeLvl.at(1) == level)//horde 2
  133. if(hasBuilt(BuildingID::HORDE_2))
  134. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  135. //statue-of-legion-like bonus: % to base+castle
  136. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(BonusType::CREATURE_GROWTH_PERCENT));
  137. for(const auto & b : *bonuses2)
  138. {
  139. const auto growth = b->val * (base + castleBonus) / 100;
  140. ret.entries.emplace_back(growth, b->Description(growth));
  141. }
  142. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  143. TConstBonusListPtr bonuses = getBonuses(Selector::typeSubtype(BonusType::CREATURE_GROWTH, BonusSubtypeID::creatureLevel(level)));
  144. for(const auto & b : *bonuses)
  145. ret.entries.emplace_back(b->val, b->Description());
  146. int dwellingBonus = 0;
  147. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  148. {
  149. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  150. }
  151. if(dwellingBonus)
  152. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  153. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  154. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  155. return ret;
  156. }
  157. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  158. {
  159. int totalBonus = 0;
  160. for (const auto& dwelling : dwellings)
  161. {
  162. for (const auto& creature : dwelling->creatures)
  163. {
  164. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  165. }
  166. }
  167. return totalBonus;
  168. }
  169. TResources CGTownInstance::dailyIncome() const
  170. {
  171. TResources ret;
  172. for(const auto & p : town->buildings)
  173. {
  174. BuildingID buildingUpgrade;
  175. for(const auto & p2 : town->buildings)
  176. {
  177. if (p2.second->upgrade == p.first)
  178. {
  179. buildingUpgrade = p2.first;
  180. }
  181. }
  182. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  183. {
  184. ret += p.second->produce;
  185. }
  186. }
  187. return ret;
  188. }
  189. bool CGTownInstance::hasFort() const
  190. {
  191. return hasBuilt(BuildingID::FORT);
  192. }
  193. bool CGTownInstance::hasCapitol() const
  194. {
  195. return hasBuilt(BuildingID::CAPITOL);
  196. }
  197. CGTownInstance::CGTownInstance():
  198. town(nullptr),
  199. builded(0),
  200. destroyed(0),
  201. identifier(0),
  202. alignmentToPlayer(PlayerColor::NEUTRAL)
  203. {
  204. this->setNodeType(CBonusSystemNode::TOWN);
  205. }
  206. CGTownInstance::~CGTownInstance()
  207. {
  208. for (auto & elem : bonusingBuildings)
  209. delete elem;
  210. }
  211. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  212. {
  213. if(checkGuild && mageGuildLevel() < level)
  214. return 0;
  215. int ret = 6 - level; //how many spells are available at this level
  216. if (hasBuilt(BuildingSubID::LIBRARY))
  217. ret++;
  218. return ret;
  219. }
  220. bool CGTownInstance::needsLastStack() const
  221. {
  222. return garrisonHero != nullptr;
  223. }
  224. void CGTownInstance::setOwner(const PlayerColor & player) const
  225. {
  226. removeCapitols(player);
  227. cb->setOwner(this, player);
  228. }
  229. void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  230. {
  231. for (auto building : bonusingBuildings)
  232. building->blockingDialogAnswered(hero, answer);
  233. }
  234. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  235. {
  236. if(cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)
  237. {
  238. if(armedGarrison() || visitingHero)
  239. {
  240. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  241. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  242. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  243. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  244. {
  245. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  246. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  247. if(nodeSiege == (CBonusSystemNode *)this)
  248. cb->swapGarrisonOnSiege(this->id);
  249. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  250. }
  251. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  252. }
  253. else
  254. {
  255. auto heroColor = h->getOwner();
  256. onTownCaptured(heroColor);
  257. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  258. {
  259. return; //we just won game, we do not need to perform any extra actions
  260. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  261. }
  262. cb->heroVisitCastle(this, h);
  263. }
  264. }
  265. else if(h->visitablePos() == visitablePos())
  266. {
  267. bool commander_recover = h->commander && !h->commander->alive;
  268. if (commander_recover) // rise commander from dead
  269. {
  270. SetCommanderProperty scp;
  271. scp.heroid = h->id;
  272. scp.which = SetCommanderProperty::ALIVE;
  273. scp.amount = 1;
  274. cb->sendAndApply(&scp);
  275. }
  276. cb->heroVisitCastle(this, h);
  277. // TODO(vmarkovtsev): implement payment for rising the commander
  278. if (commander_recover) // info window about commander
  279. {
  280. InfoWindow iw;
  281. iw.player = h->tempOwner;
  282. iw.text.appendRawString(h->commander->getName());
  283. iw.components.emplace_back(*h->commander);
  284. cb->showInfoDialog(&iw);
  285. }
  286. }
  287. else
  288. {
  289. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), getNameTranslated());
  290. }
  291. }
  292. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  293. {
  294. //FIXME: find out why this issue appears on random maps
  295. if(visitingHero == h)
  296. {
  297. cb->stopHeroVisitCastle(this, h);
  298. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), getNameTranslated());
  299. }
  300. else
  301. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), getNameTranslated());
  302. }
  303. std::string CGTownInstance::getObjectName() const
  304. {
  305. return getNameTranslated() + ", " + town->faction->getNameTranslated();
  306. }
  307. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  308. {
  309. return town->getBuildingType(subId) != BuildingID::NONE;
  310. }
  311. void CGTownInstance::initOverriddenBids()
  312. {
  313. for(const auto & bid : builtBuildings)
  314. {
  315. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  316. for(const auto & overrideIt : overrideThem)
  317. overriddenBuildings.insert(overrideIt);
  318. }
  319. }
  320. bool CGTownInstance::isBonusingBuildingAdded(BuildingID bid) const
  321. {
  322. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  323. {
  324. return building->getBuildingType().num == bid;
  325. });
  326. return present != bonusingBuildings.end();
  327. }
  328. void CGTownInstance::addTownBonuses(CRandomGenerator & rand)
  329. {
  330. for(const auto & kvp : town->buildings)
  331. {
  332. if(vstd::contains(overriddenBuildings, kvp.first))
  333. continue;
  334. if(kvp.second->IsVisitingBonus())
  335. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  336. if(kvp.second->IsWeekBonus())
  337. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  338. if(kvp.second->subId == BuildingSubID::CUSTOM_VISITING_REWARD)
  339. bonusingBuildings.push_back(new CTownRewardableBuilding(kvp.second->bid, kvp.second->subId, this, rand));
  340. }
  341. }
  342. DamageRange CGTownInstance::getTowerDamageRange() const
  343. {
  344. assert(hasBuilt(BuildingID::CASTLE));
  345. // http://heroes.thelazy.net/wiki/Arrow_tower
  346. // base damage, irregardless of town level
  347. static constexpr int baseDamage = 6;
  348. // extra damage, for each building in town
  349. static constexpr int extraDamage = 1;
  350. const int minDamage = baseDamage + extraDamage * getTownLevel();
  351. return {
  352. minDamage,
  353. minDamage * 2
  354. };
  355. }
  356. DamageRange CGTownInstance::getKeepDamageRange() const
  357. {
  358. assert(hasBuilt(BuildingID::CITADEL));
  359. // http://heroes.thelazy.net/wiki/Arrow_tower
  360. // base damage, irregardless of town level
  361. static constexpr int baseDamage = 10;
  362. // extra damage, for each building in town
  363. static constexpr int extraDamage = 2;
  364. const int minDamage = baseDamage + extraDamage * getTownLevel();
  365. return {
  366. minDamage,
  367. minDamage * 2
  368. };
  369. }
  370. void CGTownInstance::deleteTownBonus(BuildingID bid)
  371. {
  372. size_t i = 0;
  373. CGTownBuilding * freeIt = nullptr;
  374. for(i = 0; i != bonusingBuildings.size(); i++)
  375. {
  376. if(bonusingBuildings[i]->getBuildingType() == bid)
  377. {
  378. freeIt = bonusingBuildings[i];
  379. break;
  380. }
  381. }
  382. if(freeIt == nullptr)
  383. return;
  384. auto building = town->buildings.at(bid);
  385. auto isVisitingBonus = building->IsVisitingBonus();
  386. auto isWeekBonus = building->IsWeekBonus();
  387. if(!isVisitingBonus && !isWeekBonus)
  388. return;
  389. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  390. delete freeIt;
  391. }
  392. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  393. {
  394. blockVisit = true;
  395. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  396. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  397. else
  398. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  399. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  400. {
  401. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST + level);
  402. int upgradeNum = 0;
  403. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  404. {
  405. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  406. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  407. }
  408. }
  409. initOverriddenBids();
  410. addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector.
  411. recreateBuildingsBonuses();
  412. updateAppearance();
  413. }
  414. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  415. {
  416. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  417. {
  418. //give resources if there's a Mystic Pond
  419. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  420. && cb->getDate(Date::DAY) != 1
  421. && (tempOwner.isValidPlayer())
  422. )
  423. {
  424. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  425. resID = (resID==2)?1:resID;
  426. int resVal = rand.nextInt(1, 4);//with size 1..4
  427. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  428. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  429. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  430. }
  431. for(const auto * manaVortex : getBonusingBuildings(BuildingSubID::MANA_VORTEX))
  432. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  433. //get Mana Vortex or Stables bonuses
  434. //same code is in the CGameHandler::buildStructure method
  435. if (visitingHero != nullptr)
  436. cb->visitCastleObjects(this, visitingHero);
  437. if (garrisonHero != nullptr)
  438. cb->visitCastleObjects(this, garrisonHero);
  439. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  440. {
  441. std::vector<SlotID> nativeCrits; //slots
  442. for(const auto & elem : Slots())
  443. {
  444. if (elem.second->type->getFaction() == getFaction()) //native
  445. {
  446. nativeCrits.push_back(elem.first); //collect matching slots
  447. }
  448. }
  449. if(!nativeCrits.empty())
  450. {
  451. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  452. StackLocation sl(this, pos);
  453. const CCreature *c = getCreature(pos);
  454. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  455. {
  456. cb->changeStackCount(sl, c->getGrowth());
  457. }
  458. else //upgrade
  459. {
  460. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  461. }
  462. }
  463. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  464. {
  465. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  466. if (!town->creatures[i].empty())
  467. {
  468. CreatureID c = town->creatures[i][0];
  469. SlotID n;
  470. TQuantity count = creatureGrowth(i);
  471. if (!count) // no dwelling
  472. count = VLC->creatures()->getByIndex(c)->getGrowth();
  473. {//no lower tiers or above current month
  474. if ((n = getSlotFor(c)).validSlot())
  475. {
  476. StackLocation sl(this, n);
  477. if (slotEmpty(n))
  478. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  479. else //add to existing
  480. cb->changeStackCount(sl, count);
  481. }
  482. }
  483. }
  484. }
  485. }
  486. }
  487. for(const auto * rewardableBuilding : getBonusingBuildings(BuildingSubID::CUSTOM_VISITING_REWARD))
  488. rewardableBuilding->newTurn(rand);
  489. }
  490. /*
  491. int3 CGTownInstance::getSightCenter() const
  492. {
  493. return pos - int3(2,0,0);
  494. }
  495. */
  496. bool CGTownInstance::passableFor(PlayerColor color) const
  497. {
  498. if (!armedGarrison())//empty castle - anyone can visit
  499. return true;
  500. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  501. return false;
  502. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  503. }
  504. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  505. {
  506. offsets = {int3(-1,2,0), int3(+1,2,0)};
  507. }
  508. CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
  509. {
  510. if (!hasBuilt(BuildingID::SHIPYARD))
  511. return EGeneratorState::UNKNOWN;
  512. return IShipyard::shipyardStatus();
  513. }
  514. const IObjectInterface * CGTownInstance::getObject() const
  515. {
  516. return this;
  517. }
  518. void CGTownInstance::mergeGarrisonOnSiege() const
  519. {
  520. auto getWeakestStackSlot = [&](ui64 powerLimit)
  521. {
  522. std::vector<SlotID> weakSlots;
  523. auto stacksList = visitingHero->stacks;
  524. std::pair<SlotID, CStackInstance *> pair;
  525. while(!stacksList.empty())
  526. {
  527. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  528. if(powerLimit > pair.second->getPower() &&
  529. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  530. {
  531. weakSlots.push_back(pair.first);
  532. stacksList.erase(pair.first);
  533. }
  534. else
  535. break;
  536. }
  537. if(!weakSlots.empty())
  538. return *std::max_element(weakSlots.begin(), weakSlots.end());
  539. return SlotID();
  540. };
  541. auto count = static_cast<int>(stacks.size());
  542. for(int i = 0; i < count; i++)
  543. {
  544. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  545. {
  546. ui64 power = elem.second->getPower();
  547. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  548. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  549. power += visitingHero->getStack(dst).getPower();
  550. return power;
  551. });
  552. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  553. if(dst.validSlot())
  554. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  555. else
  556. {
  557. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  558. if(dst.validSlot())
  559. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  560. }
  561. }
  562. }
  563. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  564. {
  565. if (hasCapitol()) // search if there's an older capitol
  566. {
  567. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  568. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  569. {
  570. if (*i != this && (*i)->hasCapitol())
  571. {
  572. RazeStructures rs;
  573. rs.tid = id;
  574. rs.bid.insert(BuildingID::CAPITOL);
  575. rs.destroyed = destroyed;
  576. cb->sendAndApply(&rs);
  577. return;
  578. }
  579. }
  580. }
  581. }
  582. void CGTownInstance::clearArmy() const
  583. {
  584. while(!stacks.empty())
  585. {
  586. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  587. }
  588. }
  589. BoatId CGTownInstance::getBoatType() const
  590. {
  591. return town->faction->boatType;
  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 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 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 " + getNameTranslated();
  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()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  677. if(!b)
  678. {
  679. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, TBonusSourceID());
  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()(BonusSource::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 VLC->generaltexth->translate(nameTextId);
  791. }
  792. void CGTownInstance::setNameTextId( const std::string & newName )
  793. {
  794. nameTextId = 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!", getNameTranslated(), 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. if (town->buildings.count(id) == 0)
  859. {
  860. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  861. return CBuilding::TRequired::OperatorAll();
  862. }
  863. const CBuilding * build = town->buildings.at(id);
  864. CBuilding::TRequired::OperatorAll requirements;
  865. if (!hasBuilt(id))
  866. {
  867. if (deep)
  868. requirements.expressions.emplace_back(id);
  869. else
  870. return id;
  871. }
  872. if(!vstd::contains(processed, id))
  873. {
  874. processed.insert(id);
  875. if (build->upgrade != BuildingID::NONE)
  876. requirements.expressions.push_back(dependTest(build->upgrade));
  877. requirements.expressions.push_back(build->requirements.morph(dependTest));
  878. }
  879. return requirements;
  880. };
  881. CBuilding::TRequired::OperatorAll requirements;
  882. if (building->upgrade != BuildingID::NONE)
  883. {
  884. const CBuilding * upgr = town->buildings.at(building->upgrade);
  885. requirements.expressions.push_back(dependTest(upgr->bid));
  886. processed.clear();
  887. }
  888. requirements.expressions.push_back(building->requirements.morph(dependTest));
  889. CBuilding::TRequired::Variant variant(requirements);
  890. CBuilding::TRequired ret(variant);
  891. ret.minimize();
  892. return ret;
  893. }
  894. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  895. {
  896. if(visitingHero == h)
  897. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  898. else if(garrisonHero == h)
  899. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  900. else
  901. {
  902. //should never ever happen
  903. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  904. throw std::runtime_error("internal error");
  905. }
  906. }
  907. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  908. {
  909. if(result.winner == BattleSide::ATTACKER)
  910. {
  911. clearArmy();
  912. onTownCaptured(hero->getOwner());
  913. }
  914. }
  915. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  916. {
  917. setOwner(winner);
  918. cb->changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  919. }
  920. void CGTownInstance::afterAddToMap(CMap * map)
  921. {
  922. if(ID == Obj::TOWN)
  923. map->towns.emplace_back(this);
  924. }
  925. void CGTownInstance::afterRemoveFromMap(CMap * map)
  926. {
  927. if (ID == Obj::TOWN)
  928. vstd::erase_if_present(map->towns, this);
  929. }
  930. void CGTownInstance::reset()
  931. {
  932. CGTownInstance::merchantArtifacts.clear();
  933. CGTownInstance::universitySkills.clear();
  934. }
  935. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  936. {
  937. CGObjectInstance::serializeJsonOwner(handler);
  938. if(!handler.saving)
  939. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  940. CArmedInstance::serializeJsonOptions(handler);
  941. handler.serializeString("name", nameTextId);
  942. {
  943. auto decodeBuilding = [this](const std::string & identifier) -> si32
  944. {
  945. auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  946. if(rawId)
  947. return rawId.value();
  948. else
  949. return -1;
  950. };
  951. auto encodeBuilding = [this](si32 index) -> std::string
  952. {
  953. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  954. };
  955. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  956. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  957. if(handler.saving)
  958. {
  959. bool customBuildings = false;
  960. boost::logic::tribool hasFort(false);
  961. for(const BuildingID & id : forbiddenBuildings)
  962. {
  963. buildingsLIC.none.insert(id);
  964. customBuildings = true;
  965. }
  966. for(const BuildingID & id : builtBuildings)
  967. {
  968. if(id == BuildingID::DEFAULT)
  969. continue;
  970. const CBuilding * building = getTown()->buildings.at(id);
  971. if(building->mode == CBuilding::BUILD_AUTO)
  972. continue;
  973. if(id == BuildingID::FORT)
  974. hasFort = true;
  975. buildingsLIC.all.insert(id);
  976. customBuildings = true;
  977. }
  978. if(customBuildings)
  979. handler.serializeLIC("buildings", buildingsLIC);
  980. else
  981. handler.serializeBool("hasFort",hasFort);
  982. }
  983. else
  984. {
  985. handler.serializeLIC("buildings", buildingsLIC);
  986. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  987. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  988. {
  989. builtBuildings.insert(BuildingID::DEFAULT);
  990. bool hasFort = false;
  991. handler.serializeBool("hasFort",hasFort);
  992. if(hasFort)
  993. builtBuildings.insert(BuildingID::FORT);
  994. }
  995. else
  996. {
  997. for(const si32 item : buildingsLIC.none)
  998. forbiddenBuildings.insert(BuildingID(item));
  999. for(const si32 item : buildingsLIC.all)
  1000. builtBuildings.insert(BuildingID(item));
  1001. }
  1002. }
  1003. }
  1004. {
  1005. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1006. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1007. if(handler.saving)
  1008. {
  1009. for(const SpellID & id : possibleSpells)
  1010. spellsLIC.any[id.num] = true;
  1011. for(const SpellID & id : obligatorySpells)
  1012. spellsLIC.all[id.num] = true;
  1013. }
  1014. handler.serializeLIC("spells", spellsLIC);
  1015. if(!handler.saving)
  1016. {
  1017. possibleSpells.clear();
  1018. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1019. {
  1020. if(spellsLIC.any[idx])
  1021. possibleSpells.emplace_back(idx);
  1022. }
  1023. obligatorySpells.clear();
  1024. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1025. {
  1026. if(spellsLIC.all[idx])
  1027. obligatorySpells.emplace_back(idx);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. FactionID CGTownInstance::getFaction() const
  1033. {
  1034. return town->faction->getId();
  1035. }
  1036. TerrainId CGTownInstance::getNativeTerrain() const
  1037. {
  1038. return town->faction->getNativeTerrain();
  1039. }
  1040. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1041. : count(_count)
  1042. {
  1043. description = boost::str(boost::format(format) % count);
  1044. }
  1045. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1046. {
  1047. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1048. }
  1049. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1050. count(_count),
  1051. description(std::move(fullDescription))
  1052. {
  1053. }
  1054. CTownAndVisitingHero::CTownAndVisitingHero()
  1055. {
  1056. setNodeType(TOWN_AND_VISITOR);
  1057. }
  1058. int GrowthInfo::totalGrowth() const
  1059. {
  1060. int ret = 0;
  1061. for(const Entry &entry : entries)
  1062. ret += entry.count;
  1063. return ret;
  1064. }
  1065. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1066. {
  1067. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1068. {
  1069. if (vstd::contains(dwelling.second, stack.type->getId())) //Dwelling with our creature
  1070. {
  1071. for(const auto & upgrID : dwelling.second)
  1072. {
  1073. if(vstd::contains(stack.type->upgrades, upgrID)) //possible upgrade
  1074. {
  1075. info.newID.push_back(upgrID);
  1076. info.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost());
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. VCMI_LIB_NAMESPACE_END