CGTownInstance.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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 "TownBuildingInstance.h"
  13. #include "../IGameSettings.h"
  14. #include "../spells/CSpellHandler.h"
  15. #include "../bonuses/Bonus.h"
  16. #include "../battle/IBattleInfoCallback.h"
  17. #include "../battle/BattleLayout.h"
  18. #include "../CConfigHandler.h"
  19. #include "../texts/CGeneralTextHandler.h"
  20. #include "../gameState/CGameState.h"
  21. #include "../gameState/UpgradeInfo.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../StartInfo.h"
  25. #include "../TerrainHandler.h"
  26. #include "../callback/IGameInfoCallback.h"
  27. #include "../callback/IGameEventCallback.h"
  28. #include "../callback/IGameRandomizer.h"
  29. #include "../entities/building/CBuilding.h"
  30. #include "../entities/faction/CTownHandler.h"
  31. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  32. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  33. #include "../mapObjects/CGHeroInstance.h"
  34. #include "../modding/ModScope.h"
  35. #include "../networkPacks/StackLocation.h"
  36. #include "../networkPacks/PacksForClient.h"
  37. #include "../networkPacks/PacksForClientBattle.h"
  38. #include "../serializer/JsonSerializeFormat.h"
  39. #include <vstd/RNG.h>
  40. VCMI_LIB_NAMESPACE_BEGIN
  41. int CGTownInstance::getSightRadius() const
  42. {
  43. int baseValue = LIBRARY->engineSettings()->getInteger(EGameSettings::TOWNS_BASE_SCOUNTING_RANGE);
  44. return applyBonuses(BonusType::SIGHT_RADIUS, baseValue);
  45. }
  46. void CGTownInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  47. {
  48. ///this is freakin' overcomplicated solution
  49. switch (what)
  50. {
  51. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  52. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getVisitingHero()->id);
  53. break;
  54. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  55. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0));
  56. break;
  57. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  58. rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, getGarrisonHero()->id);
  59. break;
  60. case ObjProperty::BONUS_VALUE_FIRST:
  61. bonusValue.first = identifier.getNum();
  62. break;
  63. case ObjProperty::BONUS_VALUE_SECOND:
  64. bonusValue.second = identifier.getNum();
  65. break;
  66. }
  67. }
  68. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  69. {
  70. if (hasBuilt(BuildingID::CASTLE))
  71. return CASTLE;
  72. if (hasBuilt(BuildingID::CITADEL))
  73. return CITADEL;
  74. if (hasBuilt(BuildingID::FORT))
  75. return FORT;
  76. return NONE;
  77. }
  78. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  79. {
  80. if (hasBuilt(BuildingID::CAPITOL))
  81. return 3;
  82. if (hasBuilt(BuildingID::CITY_HALL))
  83. return 2;
  84. if (hasBuilt(BuildingID::TOWN_HALL))
  85. return 1;
  86. if (hasBuilt(BuildingID::VILLAGE_HALL))
  87. return 0;
  88. return -1;
  89. }
  90. int CGTownInstance::mageGuildLevel() const
  91. {
  92. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  93. return 5;
  94. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  95. return 4;
  96. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  97. return 3;
  98. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  99. return 2;
  100. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  101. return 1;
  102. return 0;
  103. }
  104. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  105. {
  106. return getTown()->hordeLvl.at(HID);
  107. }
  108. int CGTownInstance::creatureGrowth(const int & level) const
  109. {
  110. return getGrowthInfo(level).totalGrowth();
  111. }
  112. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  113. {
  114. GrowthInfo ret;
  115. if (level<0 || level >=getTown()->creatures.size())
  116. return ret;
  117. if (creatures[level].second.empty())
  118. return ret; //no dwelling
  119. const Creature *creature = creatures[level].second.back().toEntity(LIBRARY);
  120. const int base = creature->getGrowth();
  121. int castleBonus = 0;
  122. if(tempOwner.isValidPlayer())
  123. {
  124. auto * playerSettings = cb->getPlayerSettings(tempOwner);
  125. ret.handicapPercentage = playerSettings->handicap.percentGrowth;
  126. }
  127. else
  128. ret.handicapPercentage = 100;
  129. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  130. if (hasBuilt(BuildingID::CASTLE))
  131. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  132. else if (hasBuilt(BuildingID::CITADEL))
  133. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  134. if(getTown()->hordeLvl.at(0) == level)//horde 1
  135. if(hasBuilt(BuildingID::HORDE_1))
  136. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  137. if(getTown()->hordeLvl.at(1) == level)//horde 2
  138. if(hasBuilt(BuildingID::HORDE_2))
  139. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  140. //statue-of-legion-like bonus: % to base+castle
  141. TConstBonusListPtr bonuses2 = getBonusesOfType(BonusType::CREATURE_GROWTH_PERCENT);
  142. for(const auto & b : *bonuses2)
  143. {
  144. const auto growth = b->val * (base + castleBonus) / 100;
  145. if (growth)
  146. {
  147. ret.entries.emplace_back(growth, b->Description(cb, growth));
  148. }
  149. }
  150. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  151. // Note: bonus uses 1-based levels (Pikeman is level 1), town list uses 0-based (Pikeman in 0-th creatures entry)
  152. TConstBonusListPtr bonuses = getBonusesOfType(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(level+1));
  153. for(const auto & b : *bonuses)
  154. ret.entries.emplace_back(b->val, b->Description(cb));
  155. int dwellingBonus = 0;
  156. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  157. {
  158. dwellingBonus = getDwellingBonus(creatures[level].second, p->getOwnedObjects());
  159. }
  160. if(dwellingBonus)
  161. ret.entries.emplace_back(LIBRARY->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  162. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  163. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  164. return ret;
  165. }
  166. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<const CGObjectInstance * >& dwellings) const
  167. {
  168. int totalBonus = 0;
  169. for (const auto& dwelling : dwellings)
  170. {
  171. const auto & dwellingCreatures = dwelling->asOwnable()->providedCreatures();
  172. bool hasMatch = false;
  173. for (const auto& creature : dwellingCreatures)
  174. hasMatch |= vstd::contains(creatureIds, creature);
  175. if (hasMatch)
  176. totalBonus += 1;
  177. }
  178. return totalBonus;
  179. }
  180. TResources CGTownInstance::dailyIncome() const
  181. {
  182. TResources ret;
  183. for(const auto & p : getTown()->buildings)
  184. {
  185. BuildingID buildingUpgrade;
  186. for(const auto & p2 : getTown()->buildings)
  187. {
  188. if (p2.second->upgrade == p.first)
  189. {
  190. buildingUpgrade = p2.first;
  191. }
  192. }
  193. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  194. {
  195. ret += p.second->produce;
  196. }
  197. }
  198. if (!getOwner().isValidPlayer())
  199. return ret;
  200. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  201. ret.applyHandicap(playerSettings->handicap.percentIncome);
  202. return ret;
  203. }
  204. std::vector<CreatureID> CGTownInstance::providedCreatures() const
  205. {
  206. return {};
  207. }
  208. bool CGTownInstance::hasFort() const
  209. {
  210. return hasBuilt(BuildingID::FORT);
  211. }
  212. bool CGTownInstance::hasCapitol() const
  213. {
  214. return hasBuilt(BuildingID::CAPITOL);
  215. }
  216. TownFortifications CGTownInstance::fortificationsLevel() const
  217. {
  218. auto result = getTown()->fortifications;
  219. for (auto const & buildingID : builtBuildings)
  220. result += getTown()->buildings.at(buildingID)->fortifications;
  221. if (result.wallsHealth == 0)
  222. return TownFortifications();
  223. return result;
  224. }
  225. CGTownInstance::CGTownInstance(IGameInfoCallback *cb):
  226. CGDwelling(cb),
  227. IMarket(cb),
  228. built(0),
  229. destroyed(0),
  230. identifier(0),
  231. alignmentToPlayer(PlayerColor::NEUTRAL),
  232. spellResearchCounterDay(0),
  233. spellResearchAcceptedCounter(0),
  234. spellResearchAllowed(true)
  235. {
  236. setNodeType(CBonusSystemNode::TOWN);
  237. attachTo(townAndVis);
  238. }
  239. CGTownInstance::~CGTownInstance() = default;
  240. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  241. {
  242. if(checkGuild && mageGuildLevel() < level)
  243. return 0;
  244. int ret = 6 - level; //how many spells are available at this level
  245. if (hasBuilt(BuildingSubID::LIBRARY))
  246. ret++;
  247. return ret;
  248. }
  249. bool CGTownInstance::needsLastStack() const
  250. {
  251. return getGarrisonHero() != nullptr;
  252. }
  253. void CGTownInstance::setOwner(IGameEventCallback & gameEvents, const PlayerColor & player) const
  254. {
  255. removeCapitols(gameEvents, player);
  256. gameEvents.setOwner(this, player);
  257. }
  258. void CGTownInstance::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  259. {
  260. if(cb->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)
  261. {
  262. if(armedGarrison() || getVisitingHero())
  263. {
  264. const CGHeroInstance * defendingHero = getVisitingHero() ? getVisitingHero() : getGarrisonHero();
  265. const CArmedInstance * defendingArmy = defendingHero ? static_cast<const CArmedInstance*>(defendingHero) : this;
  266. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  267. if(!isBattleOutside && defendingHero == getVisitingHero())
  268. mergeGarrisonOnSiege(gameEvents);
  269. gameEvents.startBattle(h, defendingArmy, getSightCenter(), h, defendingHero, BattleLayout::createDefaultLayout(*cb, h, defendingArmy), (isBattleOutside ? nullptr : this));
  270. }
  271. else
  272. {
  273. auto heroColor = h->getOwner();
  274. onTownCaptured(gameEvents, heroColor);
  275. if(cb->gameState().getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  276. {
  277. return; //we just won game, we do not need to perform any extra actions
  278. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  279. }
  280. gameEvents.heroVisitCastle(this, h);
  281. }
  282. }
  283. else
  284. {
  285. assert(h->visitablePos() == this->visitablePos());
  286. bool commander_recover = h->getCommander() && !h->getCommander()->alive;
  287. if (commander_recover) // rise commander from dead
  288. {
  289. SetCommanderProperty scp;
  290. scp.heroid = h->id;
  291. scp.which = SetCommanderProperty::ALIVE;
  292. scp.amount = 1;
  293. gameEvents.sendAndApply(scp);
  294. }
  295. gameEvents.heroVisitCastle(this, h);
  296. // TODO(vmarkovtsev): implement payment for rising the commander
  297. if (commander_recover) // info window about commander
  298. {
  299. InfoWindow iw;
  300. iw.player = h->tempOwner;
  301. iw.text.appendRawString(h->getCommander()->getName());
  302. iw.components.emplace_back(ComponentType::CREATURE, h->getCommander()->getId(), h->getCommander()->getCount());
  303. gameEvents.showInfoDialog(&iw);
  304. }
  305. }
  306. }
  307. void CGTownInstance::onHeroLeave(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  308. {
  309. //FIXME: find out why this issue appears on random maps
  310. if(getVisitingHero() == h)
  311. {
  312. gameEvents.stopHeroVisitCastle(this, h);
  313. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), getNameTranslated());
  314. }
  315. else
  316. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), getNameTranslated());
  317. }
  318. std::string CGTownInstance::getObjectName() const
  319. {
  320. if(ID == Obj::RANDOM_TOWN )
  321. return CGObjectInstance::getObjectName();
  322. return getNameTranslated() + ", " + getTown()->faction->getNameTranslated();
  323. }
  324. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  325. {
  326. return getTown()->getBuildingType(subId) != BuildingID::NONE;
  327. }
  328. void CGTownInstance::initializeConfigurableBuildings(IGameRandomizer & gameRandomizer)
  329. {
  330. for(const auto & kvp : getTown()->buildings)
  331. {
  332. if(kvp.second->rewardableObjectInfo.getParameters().isNull())
  333. continue;
  334. try {
  335. rewardableBuildings[kvp.first] = std::make_unique<TownRewardableBuildingInstance>(this, kvp.second->bid, gameRandomizer);
  336. }
  337. catch (std::runtime_error & e)
  338. {
  339. std::string buildingConfig = kvp.second->rewardableObjectInfo.getParameters().toCompactString();
  340. std::replace(buildingConfig.begin(), buildingConfig.end(), '\n', ' ');
  341. throw std::runtime_error("Failed to load rewardable building data for " + kvp.second->getJsonKey() + " Reason: " + e.what() + ", config was: " + buildingConfig);
  342. }
  343. }
  344. }
  345. DamageRange CGTownInstance::getTowerDamageRange() const
  346. {
  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. // http://heroes.thelazy.net/wiki/Arrow_tower
  361. // base damage, irregardless of town level
  362. static constexpr int baseDamage = 10;
  363. // extra damage, for each building in town
  364. static constexpr int extraDamage = 2;
  365. const int minDamage = baseDamage + extraDamage * getTownLevel();
  366. return {
  367. minDamage,
  368. minDamage * 2
  369. };
  370. }
  371. FactionID CGTownInstance::randomizeFaction(vstd::RNG & rand)
  372. {
  373. if(getOwner().isValidPlayer())
  374. return cb->getStartInfo()->getIthPlayersSettings(getOwner()).castle;
  375. if(alignmentToPlayer.isValidPlayer())
  376. return cb->getStartInfo()->getIthPlayersSettings(alignmentToPlayer).castle;
  377. std::vector<FactionID> potentialPicks;
  378. for (FactionID faction(0); faction < FactionID(LIBRARY->townh->size()); ++faction)
  379. if (LIBRARY->factions()->getById(faction)->hasTown())
  380. potentialPicks.push_back(faction);
  381. assert(!potentialPicks.empty());
  382. return *RandomGeneratorUtil::nextItem(potentialPicks, rand);
  383. }
  384. void CGTownInstance::pickRandomObject(IGameRandomizer & gameRandomizer)
  385. {
  386. assert(ID == MapObjectID::TOWN || ID == MapObjectID::RANDOM_TOWN);
  387. if (ID == MapObjectID::RANDOM_TOWN)
  388. {
  389. ID = MapObjectID::TOWN;
  390. subID = randomizeFaction(gameRandomizer.getDefault());
  391. }
  392. assert(ID == Obj::TOWN); // just in case
  393. setType(ID, subID);
  394. randomizeArmy(getFactionID());
  395. updateAppearance();
  396. }
  397. void CGTownInstance::initObj(IGameRandomizer & gameRandomizer) ///initialize town structures
  398. {
  399. blockVisit = true;
  400. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  401. creatures.resize(getTown()->creatures.size() + 1);
  402. else
  403. creatures.resize(getTown()->creatures.size());
  404. for (int level = 0; level < getTown()->creatures.size(); level++)
  405. {
  406. BuildingID buildID = BuildingID(BuildingID::getDwellingFromLevel(level, 0));
  407. int upgradeNum = 0;
  408. for (; getTown()->buildings.count(buildID); upgradeNum++, BuildingID::advanceDwelling(buildID))
  409. {
  410. if (hasBuilt(buildID) && getTown()->creatures.at(level).size() > upgradeNum)
  411. creatures[level].second.push_back(getTown()->creatures[level][upgradeNum]);
  412. }
  413. }
  414. initializeConfigurableBuildings(gameRandomizer);
  415. initializeNeutralTownGarrison(gameRandomizer.getDefault());
  416. recreateBuildingsBonuses();
  417. updateAppearance();
  418. }
  419. void CGTownInstance::initializeNeutralTownGarrison(vstd::RNG & rand)
  420. {
  421. struct RandomGuardsInfo{
  422. int tier;
  423. int chance;
  424. int min;
  425. int max;
  426. };
  427. constexpr std::array<RandomGuardsInfo, 4> randomGuards = {
  428. RandomGuardsInfo{ 0, 33, 8, 15 },
  429. RandomGuardsInfo{ 1, 33, 5, 7 },
  430. RandomGuardsInfo{ 2, 20, 3, 5 },
  431. RandomGuardsInfo{ 3, 14, 1, 3 },
  432. };
  433. // Only neutral towns may get initial garrison
  434. if (getOwner().isValidPlayer())
  435. return;
  436. // Only towns with garrison not set in map editor may get initial garrison
  437. // FIXME: H3 editor allow explicitly empty garrison, but vcmi loses this flag on load
  438. if (stacksCount() > 0)
  439. return;
  440. for (auto const & guard : randomGuards)
  441. {
  442. if (rand.nextInt(99) >= guard.chance)
  443. continue;
  444. CreatureID guardID = getTown()->creatures[guard.tier].at(0);
  445. int guardSize = rand.nextInt(guard.min, guard.max);
  446. putStack(getFreeSlot(), std::make_unique<CStackInstance>(cb, guardID, guardSize));
  447. }
  448. }
  449. void CGTownInstance::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  450. {
  451. for(const auto & building : rewardableBuildings)
  452. building.second->newTurn(gameEvents, gameRandomizer);
  453. if(hasBuilt(BuildingSubID::BANK) && bonusValue.second > 0)
  454. {
  455. TResources res;
  456. res[EGameResID::GOLD] = -500;
  457. gameEvents.giveResources(getOwner(), res);
  458. gameEvents.setObjPropertyValue(id, ObjProperty::BONUS_VALUE_SECOND, bonusValue.second - 500);
  459. }
  460. }
  461. bool CGTownInstance::passableFor(PlayerColor color) const
  462. {
  463. if (!armedGarrison())//empty castle - anyone can visit
  464. return true;
  465. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  466. return false;
  467. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  468. }
  469. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  470. {
  471. offsets = {int3(-1,2,0), int3(+1,2,0)};
  472. }
  473. CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
  474. {
  475. if (!hasBuilt(BuildingID::SHIPYARD))
  476. return EGeneratorState::UNKNOWN;
  477. return IShipyard::shipyardStatus();
  478. }
  479. const IObjectInterface * CGTownInstance::getObject() const
  480. {
  481. return this;
  482. }
  483. void CGTownInstance::mergeGarrisonOnSiege(IGameEventCallback & gameEvents) const
  484. {
  485. auto getWeakestStackSlot = [&](ui64 powerLimit)
  486. {
  487. SlotID weakestSlot;
  488. for ( const auto & pair : getVisitingHero()->stacks)
  489. {
  490. if(powerLimit > pair.second->getPower() &&
  491. (weakestSlot == SlotID() || pair.second->getPower() < getVisitingHero()->getStack(weakestSlot).getPower()))
  492. {
  493. weakestSlot = pair.first;
  494. }
  495. }
  496. return weakestSlot;
  497. };
  498. auto count = static_cast<int>(stacks.size());
  499. for(int i = 0; i < count; i++)
  500. {
  501. const auto & pair = *vstd::maxElementByFun(stacks, [&](const auto & elem)
  502. {
  503. ui64 power = elem.second->getPower();
  504. auto dst = getVisitingHero()->getSlotFor(elem.second->getCreatureID());
  505. if(dst.validSlot() && getVisitingHero()->hasStackAtSlot(dst))
  506. power += getVisitingHero()->getStack(dst).getPower();
  507. return power;
  508. });
  509. auto dst = getVisitingHero()->getSlotFor(pair.second->getCreatureID());
  510. if(dst.validSlot())
  511. gameEvents.moveStack(StackLocation(id, pair.first), StackLocation(getVisitingHero()->id, dst), -1);
  512. else
  513. {
  514. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  515. if(dst.validSlot())
  516. gameEvents.swapStacks(StackLocation(id, pair.first), StackLocation(getVisitingHero()->id, dst));
  517. }
  518. }
  519. }
  520. void CGTownInstance::removeCapitols(IGameEventCallback & gameEvents, const PlayerColor & owner) const
  521. {
  522. if (hasCapitol()) // search if there's an older capitol
  523. {
  524. const PlayerState* state = cb->getPlayerState(owner); //get all towns owned by player
  525. for (const auto & otherTown : state->getTowns())
  526. {
  527. if (otherTown != this && otherTown->hasCapitol())
  528. {
  529. RazeStructures rs;
  530. rs.tid = id;
  531. rs.bid.insert(BuildingID::CAPITOL);
  532. rs.destroyed = destroyed;
  533. gameEvents.sendAndApply(rs);
  534. return;
  535. }
  536. }
  537. }
  538. }
  539. void CGTownInstance::clearArmy(IGameEventCallback & gameEvents) const
  540. {
  541. while(!stacks.empty())
  542. {
  543. gameEvents.eraseStack(StackLocation(id, stacks.begin()->first), true);
  544. }
  545. }
  546. BoatId CGTownInstance::getBoatType() const
  547. {
  548. return getTown()->faction->boatType;
  549. }
  550. int CGTownInstance::getMarketEfficiency() const
  551. {
  552. if(!hasBuiltSomeTradeBuilding())
  553. return 0;
  554. const PlayerState *p = cb->getPlayerState(tempOwner);
  555. assert(p);
  556. int marketCount = 0;
  557. for(const CGTownInstance *t : p->getTowns())
  558. if(t->hasBuiltSomeTradeBuilding())
  559. marketCount++;
  560. return marketCount;
  561. }
  562. std::vector<TradeItemBuy> CGTownInstance::availableItemsIds(EMarketMode mode) const
  563. {
  564. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  565. {
  566. std::vector<TradeItemBuy> ret;
  567. for(const ArtifactID a : cb->gameState().getMap().townMerchantArtifacts)
  568. ret.push_back(a);
  569. return ret;
  570. }
  571. else if ( mode == EMarketMode::RESOURCE_SKILL )
  572. {
  573. for (const auto & buildingID : builtBuildings)
  574. {
  575. const auto * buildingPtr = getTown()->buildings.at(buildingID).get();
  576. if (vstd::contains(buildingPtr->marketModes, mode))
  577. return buildingPtr->marketOffer;
  578. }
  579. logMod->warn("Town has resource-skill trade but has no skills to offer!");
  580. return {};
  581. }
  582. else
  583. return IMarket::availableItemsIds(mode);
  584. }
  585. ObjectInstanceID CGTownInstance::getObjInstanceID() const
  586. {
  587. return id;
  588. }
  589. void CGTownInstance::updateAppearance()
  590. {
  591. auto terrain = cb->getTile(visitablePos())->getTerrainID();
  592. //FIXME: not the best way to do this
  593. auto app = getObjectHandler()->getOverride(terrain, this);
  594. if (app)
  595. appearance = app;
  596. }
  597. std::string CGTownInstance::nodeName() const
  598. {
  599. return "Town (" + getTown()->faction->getNameTranslated() + ") of " + getNameTranslated();
  600. }
  601. void CGTownInstance::updateMoraleBonusFromArmy()
  602. {
  603. auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
  604. if(!b)
  605. {
  606. b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
  607. addNewBonus(b);
  608. }
  609. if (getGarrisonHero())
  610. {
  611. b->val = 0;
  612. nodeHasChanged();
  613. }
  614. else
  615. CArmedInstance::updateMoraleBonusFromArmy();
  616. }
  617. void CGTownInstance::recreateBuildingsBonuses()
  618. {
  619. BonusList bl;
  620. getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
  621. for(const auto & b : bl)
  622. removeBonus(b);
  623. for(const auto & bid : builtBuildings)
  624. {
  625. bool bonusesReplacedByUpgrade = false;
  626. for(const auto & upgradeID : builtBuildings)
  627. {
  628. const auto & upgrade = getTown()->buildings.at(upgradeID);
  629. if (upgrade->getBase() == bid && upgrade->upgradeReplacesBonuses)
  630. bonusesReplacedByUpgrade = true;
  631. }
  632. // bonuses from this building are disabled and replaced by bonuses from an upgrade
  633. if (bonusesReplacedByUpgrade)
  634. continue;
  635. const auto & building = getTown()->buildings.at(bid);
  636. if(building->buildingBonuses.empty())
  637. continue;
  638. for(auto & bonus : building->buildingBonuses)
  639. {
  640. // Add copy of bonus to bonus system
  641. // Othervice, bonuses with player or global propagator will not stack if player has multiple towns of same faction
  642. auto bonusCopy = std::make_shared<Bonus>(*bonus);
  643. addNewBonus(bonusCopy);
  644. }
  645. }
  646. }
  647. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  648. {
  649. if(getVisitingHero() == h)
  650. return;
  651. if(h)
  652. {
  653. h->detachFromBonusSystem(cb->gameState());
  654. h->setVisitedTown(this, false);
  655. h->attachToBonusSystem(cb->gameState());
  656. visitingHero = h->id;
  657. }
  658. else if (visitingHero.hasValue())
  659. {
  660. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(visitingHero));
  661. oldVisitor->detachFromBonusSystem(cb->gameState());
  662. oldVisitor->setVisitedTown(nullptr, false);
  663. oldVisitor->attachToBonusSystem(cb->gameState());
  664. visitingHero = {};
  665. }
  666. }
  667. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  668. {
  669. if(getGarrisonHero() == h)
  670. return;
  671. if(h)
  672. {
  673. h->detachFromBonusSystem(cb->gameState());
  674. h->setVisitedTown(this, true);
  675. h->attachToBonusSystem(cb->gameState());
  676. garrisonHero = h->id;
  677. }
  678. else if (garrisonHero.hasValue())
  679. {
  680. auto oldVisitor = dynamic_cast<CGHeroInstance*>(cb->gameState().getObjInstance(garrisonHero));
  681. oldVisitor->detachFromBonusSystem(cb->gameState());
  682. oldVisitor->setVisitedTown(nullptr, false);
  683. oldVisitor->attachToBonusSystem(cb->gameState());
  684. garrisonHero = {};
  685. }
  686. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  687. }
  688. const CGHeroInstance * CGTownInstance::getVisitingHero() const
  689. {
  690. if (!visitingHero.hasValue())
  691. return nullptr;
  692. return cb->getHero(visitingHero);
  693. }
  694. const CGHeroInstance * CGTownInstance::getGarrisonHero() const
  695. {
  696. if (!garrisonHero.hasValue())
  697. return nullptr;
  698. return cb->getHero(garrisonHero);
  699. }
  700. bool CGTownInstance::armedGarrison() const
  701. {
  702. return !stacks.empty() || getGarrisonHero();
  703. }
  704. int CGTownInstance::getTownLevel() const
  705. {
  706. // count all buildings that are not upgrades
  707. int level = 0;
  708. for(const auto & bid : builtBuildings)
  709. {
  710. if(getTown()->buildings.at(bid)->upgrade == BuildingID::NONE)
  711. level++;
  712. }
  713. return level;
  714. }
  715. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  716. {
  717. return townAndVis;
  718. }
  719. std::string CGTownInstance::getNameTranslated() const
  720. {
  721. return LIBRARY->generaltexth->translate(nameTextId);
  722. }
  723. std::string CGTownInstance::getNameTextID() const
  724. {
  725. return nameTextId;
  726. }
  727. void CGTownInstance::setNameTextId( const std::string & newName )
  728. {
  729. nameTextId = newName;
  730. }
  731. const CArmedInstance * CGTownInstance::getUpperArmy() const
  732. {
  733. if(getGarrisonHero())
  734. return getGarrisonHero();
  735. return this;
  736. }
  737. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  738. {
  739. return availableModes().empty() ? false : true;
  740. }
  741. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  742. {
  743. for(const auto & bid : builtBuildings)
  744. {
  745. if(getTown()->buildings.at(bid)->subId == buildingID)
  746. return true;
  747. }
  748. return false;
  749. }
  750. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  751. {
  752. return vstd::contains(builtBuildings, buildingID);
  753. }
  754. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, FactionID townID) const
  755. {
  756. if (townID == getTown()->faction->getId() || townID == FactionID::ANY)
  757. return hasBuilt(buildingID);
  758. return false;
  759. }
  760. void CGTownInstance::addBuilding(const BuildingID & buildingID)
  761. {
  762. if(buildingID == BuildingID::NONE)
  763. return;
  764. builtBuildings.insert(buildingID);
  765. }
  766. std::set<EMarketMode> CGTownInstance::availableModes() const
  767. {
  768. std::set<EMarketMode> result;
  769. for (const auto & buildingID : builtBuildings)
  770. {
  771. const auto * buildingPtr = getTown()->buildings.at(buildingID).get();
  772. result.insert(buildingPtr->marketModes.begin(), buildingPtr->marketModes.end());
  773. }
  774. return result;
  775. }
  776. void CGTownInstance::removeBuilding(const BuildingID & buildingID)
  777. {
  778. if(!vstd::contains(builtBuildings, buildingID))
  779. return;
  780. builtBuildings.erase(buildingID);
  781. }
  782. void CGTownInstance::removeAllBuildings()
  783. {
  784. builtBuildings.clear();
  785. }
  786. std::set<BuildingID> CGTownInstance::getBuildings() const
  787. {
  788. return builtBuildings;
  789. }
  790. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  791. {
  792. if (vstd::contains(getTown()->buildings, buildingID))
  793. return getTown()->buildings.at(buildingID)->resources;
  794. else
  795. {
  796. logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), anchorPos().toString(), buildingID.toEnum());
  797. return TResources();
  798. }
  799. }
  800. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  801. {
  802. const auto & building = getTown()->buildings.at(buildID);
  803. //TODO: find better solution to prevent infinite loops
  804. std::set<BuildingID> processed;
  805. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  806. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  807. {
  808. if (getTown()->buildings.count(id) == 0)
  809. {
  810. logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
  811. return CBuilding::TRequired::OperatorAll();
  812. }
  813. const auto & build = getTown()->buildings.at(id);
  814. CBuilding::TRequired::OperatorAll requirements;
  815. if (!hasBuilt(id))
  816. {
  817. if (deep)
  818. requirements.expressions.emplace_back(id);
  819. else
  820. return id;
  821. }
  822. if(!vstd::contains(processed, id))
  823. {
  824. processed.insert(id);
  825. if (build->upgrade != BuildingID::NONE)
  826. requirements.expressions.push_back(dependTest(build->upgrade));
  827. requirements.expressions.push_back(build->requirements.morph(dependTest));
  828. }
  829. return requirements;
  830. };
  831. CBuilding::TRequired::OperatorAll requirements;
  832. if (building->upgrade != BuildingID::NONE)
  833. {
  834. const auto & upgr = getTown()->buildings.at(building->upgrade);
  835. requirements.expressions.push_back(dependTest(upgr->bid));
  836. processed.clear();
  837. }
  838. requirements.expressions.push_back(building->requirements.morph(dependTest));
  839. CBuilding::TRequired::Variant variant(requirements);
  840. CBuilding::TRequired ret(variant);
  841. ret.minimize();
  842. return ret;
  843. }
  844. void CGTownInstance::addHeroToStructureVisitors(IGameEventCallback & gameEvents, const CGHeroInstance *h, si64 structureInstanceID ) const
  845. {
  846. if(getVisitingHero() == h)
  847. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  848. else if(getGarrisonHero() == h)
  849. gameEvents.setObjPropertyValue(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  850. else
  851. {
  852. //should never ever happen
  853. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  854. throw std::runtime_error("unexpected hero in CGTownInstance::addHeroToStructureVisitors");
  855. }
  856. }
  857. void CGTownInstance::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance * hero, const BattleResult & result) const
  858. {
  859. if(result.winner == BattleSide::ATTACKER)
  860. {
  861. clearArmy(gameEvents);
  862. onTownCaptured(gameEvents, hero->getOwner());
  863. }
  864. }
  865. void CGTownInstance::onTownCaptured(IGameEventCallback & gameEvents, const PlayerColor & winner) const
  866. {
  867. setOwner(gameEvents, winner);
  868. gameEvents.changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
  869. }
  870. void CGTownInstance::afterAddToMap(CMap * map)
  871. {
  872. map->townAddedToMap(this);
  873. }
  874. void CGTownInstance::afterRemoveFromMap(CMap * map)
  875. {
  876. map->townRemovedFromMap(this);
  877. }
  878. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  879. {
  880. CGObjectInstance::serializeJsonOwner(handler);
  881. if(!handler.saving)
  882. handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
  883. CArmedInstance::serializeJsonOptions(handler);
  884. handler.serializeString("name", nameTextId);
  885. {
  886. auto decodeBuilding = [this](const std::string & identifier) -> si32
  887. {
  888. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
  889. if(rawId)
  890. return rawId.value();
  891. else
  892. return -1;
  893. };
  894. auto encodeBuilding = [this](si32 index) -> std::string
  895. {
  896. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  897. };
  898. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  899. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  900. if(handler.saving)
  901. {
  902. bool customBuildings = false;
  903. boost::logic::tribool hasFort(false);
  904. for(const BuildingID & id : forbiddenBuildings)
  905. {
  906. buildingsLIC.none.insert(id.getNum());
  907. customBuildings = true;
  908. }
  909. for(const BuildingID & id : builtBuildings)
  910. {
  911. if(id == BuildingID::DEFAULT)
  912. continue;
  913. const auto & building = getTown()->buildings.at(id);
  914. if(building->mode == CBuilding::BUILD_AUTO)
  915. continue;
  916. if(id == BuildingID::FORT)
  917. hasFort = true;
  918. buildingsLIC.all.insert(id.getNum());
  919. customBuildings = true;
  920. }
  921. if(customBuildings)
  922. handler.serializeLIC("buildings", buildingsLIC);
  923. else
  924. handler.serializeBool("hasFort",hasFort);
  925. }
  926. else
  927. {
  928. handler.serializeLIC("buildings", buildingsLIC);
  929. addBuilding(BuildingID::VILLAGE_HALL);
  930. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  931. {
  932. addBuilding(BuildingID::DEFAULT);
  933. bool hasFort = false;
  934. handler.serializeBool("hasFort",hasFort);
  935. if(hasFort)
  936. addBuilding(BuildingID::FORT);
  937. }
  938. else
  939. {
  940. for(const si32 item : buildingsLIC.none)
  941. forbiddenBuildings.insert(BuildingID(item));
  942. for(const si32 item : buildingsLIC.all)
  943. addBuilding(BuildingID(item));
  944. }
  945. }
  946. }
  947. {
  948. handler.serializeIdArray( "possibleSpells", possibleSpells);
  949. handler.serializeIdArray( "obligatorySpells", obligatorySpells);
  950. }
  951. {
  952. auto eventsHandler = handler.enterArray("events");
  953. eventsHandler.syncSize(events, JsonNode::JsonType::DATA_VECTOR);
  954. eventsHandler.serializeStruct(events);
  955. }
  956. handler.serializeId("alignmentToPlayer", alignmentToPlayer, PlayerColor::NEUTRAL);
  957. }
  958. const CFaction * CGTownInstance::getFaction() const
  959. {
  960. return getFactionID().toFaction();
  961. }
  962. const CTown * CGTownInstance::getTown() const
  963. {
  964. if(ID == Obj::RANDOM_TOWN)
  965. return LIBRARY->townh->randomFaction->town.get();
  966. return getFaction()->town.get();
  967. }
  968. FactionID CGTownInstance::getFactionID() const
  969. {
  970. return FactionID(subID.getNum());
  971. }
  972. TerrainId CGTownInstance::getNativeTerrain() const
  973. {
  974. return getTown()->faction->getNativeTerrain();
  975. }
  976. ArtifactID CGTownInstance::getWarMachineInBuilding(BuildingID building) const
  977. {
  978. if (builtBuildings.count(building) == 0)
  979. return ArtifactID::NONE;
  980. if (building == BuildingID::BLACKSMITH && getTown()->warMachineDeprecated.hasValue())
  981. return getTown()->warMachineDeprecated.toCreature()->warMachine;
  982. return getTown()->buildings.at(building)->warMachine;
  983. }
  984. bool CGTownInstance::isWarMachineAvailable(ArtifactID warMachine) const
  985. {
  986. for (auto const & buildingID : builtBuildings)
  987. if (getTown()->buildings.at(buildingID)->warMachine == warMachine)
  988. return true;
  989. if (builtBuildings.count(BuildingID::BLACKSMITH) &&
  990. getTown()->warMachineDeprecated.hasValue() &&
  991. getTown()->warMachineDeprecated.toCreature()->warMachine == warMachine)
  992. return true;
  993. return false;
  994. }
  995. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  996. : count(_count)
  997. {
  998. MetaString formatter;
  999. formatter.appendRawString(format);
  1000. formatter.replacePositiveNumber(count);
  1001. description = formatter.toString();
  1002. }
  1003. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1004. {
  1005. MetaString formatter;
  1006. formatter.appendRawString("%s %+d");
  1007. formatter.replaceRawString(FactionID(subID).toFaction()->town->buildings.at(building)->getNameTranslated());
  1008. formatter.replacePositiveNumber(count);
  1009. description = formatter.toString();
  1010. }
  1011. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1012. count(_count),
  1013. description(std::move(fullDescription))
  1014. {
  1015. }
  1016. CTownAndVisitingHero::CTownAndVisitingHero()
  1017. {
  1018. setNodeType(TOWN_AND_VISITOR);
  1019. }
  1020. int GrowthInfo::totalGrowth() const
  1021. {
  1022. int ret = 0;
  1023. for(const Entry &entry : entries)
  1024. ret += entry.count;
  1025. // always round up income - we don't want buildings to always produce zero if handicap in use
  1026. return vstd::divideAndCeil(ret * handicapPercentage, 100);
  1027. }
  1028. void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1029. {
  1030. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
  1031. {
  1032. if (vstd::contains(dwelling.second, stack.getId())) //Dwelling with our creature
  1033. {
  1034. for(const auto & upgrID : dwelling.second)
  1035. {
  1036. if(vstd::contains(stack.getCreature()->upgrades, upgrID)) //possible upgrade
  1037. {
  1038. info.addUpgrade(upgrID, stack.getType());
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. void CGTownInstance::postDeserialize()
  1045. {
  1046. for(auto & building : rewardableBuildings)
  1047. building.second->town = this;
  1048. if (getFactionID().hasValue())
  1049. {
  1050. vstd::erase_if(builtBuildings, [this](const BuildingID & buildID)
  1051. {
  1052. return getTown()->buildings.count(buildID) == 0;
  1053. });
  1054. }
  1055. }
  1056. std::map<BuildingID, TownRewardableBuildingInstance*> CGTownInstance::convertOldBuildings(std::vector<TownRewardableBuildingInstance*> oldVector)
  1057. {
  1058. std::map<BuildingID, TownRewardableBuildingInstance*> result;
  1059. for(auto & building : oldVector)
  1060. {
  1061. result[building->getBuildingType()] = new TownRewardableBuildingInstance(*building);
  1062. delete building;
  1063. }
  1064. return result;
  1065. }
  1066. VCMI_LIB_NAMESPACE_END