CGTownInstance.cpp 33 KB

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