CGTownInstance.cpp 34 KB

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