CGTownInstance.cpp 33 KB

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