CGTownInstance.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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 "CObjectClassesHandler.h"
  13. #include "../spells/CSpellHandler.h"
  14. #include "../battle/IBattleInfoCallback.h"
  15. #include "../NetPacks.h"
  16. #include "../CConfigHandler.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../IGameCallback.h"
  21. #include "../CGameState.h"
  22. #include "../mapping/CMap.h"
  23. #include "../CPlayerState.h"
  24. #include "../TerrainHandler.h"
  25. #include "../serializer/JsonSerializeFormat.h"
  26. #include "../HeroBonus.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  29. std::vector<int> CGTownInstance::universitySkills;
  30. CSpecObjInfo::CSpecObjInfo():
  31. owner(nullptr)
  32. {
  33. }
  34. void CCreGenAsCastleInfo::serializeJson(JsonSerializeFormat & handler)
  35. {
  36. handler.serializeString("sameAsTown", instanceId);
  37. if(!handler.saving)
  38. {
  39. asCastle = !instanceId.empty();
  40. allowedFactions.clear();
  41. }
  42. if(!asCastle)
  43. {
  44. std::vector<bool> standard;
  45. standard.resize(VLC->townh->size(), true);
  46. JsonSerializeFormat::LIC allowedLIC(standard, &FactionID::decode, &FactionID::encode);
  47. allowedLIC.any = allowedFactions;
  48. handler.serializeLIC("allowedFactions", allowedLIC);
  49. if(!handler.saving)
  50. {
  51. allowedFactions = allowedLIC.any;
  52. }
  53. }
  54. }
  55. void CCreGenLeveledInfo::serializeJson(JsonSerializeFormat & handler)
  56. {
  57. handler.serializeInt("minLevel", minLevel, static_cast<ui8>(1));
  58. handler.serializeInt("maxLevel", maxLevel, static_cast<ui8>(7));
  59. if(!handler.saving)
  60. {
  61. //todo: safely allow any level > 7
  62. vstd::amax(minLevel, 1);
  63. vstd::amin(minLevel, 7);
  64. vstd::abetween(maxLevel, minLevel, 7);
  65. }
  66. }
  67. void CCreGenLeveledCastleInfo::serializeJson(JsonSerializeFormat & handler)
  68. {
  69. CCreGenAsCastleInfo::serializeJson(handler);
  70. CCreGenLeveledInfo::serializeJson(handler);
  71. }
  72. CGDwelling::CGDwelling()
  73. : info(nullptr)
  74. {
  75. }
  76. CGDwelling::~CGDwelling()
  77. {
  78. vstd::clear_pointer(info);
  79. }
  80. void CGDwelling::initObj(CRandomGenerator & rand)
  81. {
  82. switch(ID)
  83. {
  84. case Obj::CREATURE_GENERATOR1:
  85. case Obj::CREATURE_GENERATOR4:
  86. {
  87. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  88. if (getOwner() != PlayerColor::NEUTRAL)
  89. cb->gameState()->players[getOwner()].dwellings.emplace_back(this);
  90. assert(!creatures.empty());
  91. assert(!creatures[0].second.empty());
  92. break;
  93. }
  94. case Obj::REFUGEE_CAMP:
  95. //is handled within newturn func
  96. break;
  97. case Obj::WAR_MACHINE_FACTORY:
  98. creatures.resize(3);
  99. creatures[0].second.emplace_back(CreatureID::BALLISTA);
  100. creatures[1].second.emplace_back(CreatureID::FIRST_AID_TENT);
  101. creatures[2].second.emplace_back(CreatureID::AMMO_CART);
  102. break;
  103. default:
  104. assert(0);
  105. break;
  106. }
  107. }
  108. void CGDwelling::initRandomObjectInfo()
  109. {
  110. vstd::clear_pointer(info);
  111. switch(ID)
  112. {
  113. case Obj::RANDOM_DWELLING: info = new CCreGenLeveledCastleInfo();
  114. break;
  115. case Obj::RANDOM_DWELLING_LVL: info = new CCreGenAsCastleInfo();
  116. break;
  117. case Obj::RANDOM_DWELLING_FACTION: info = new CCreGenLeveledInfo();
  118. break;
  119. }
  120. if(info)
  121. info->owner = this;
  122. }
  123. void CGDwelling::setPropertyDer(ui8 what, ui32 val)
  124. {
  125. switch (what)
  126. {
  127. case ObjProperty::OWNER: //change owner
  128. if (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR2
  129. || ID == Obj::CREATURE_GENERATOR3 || ID == Obj::CREATURE_GENERATOR4)
  130. {
  131. if (tempOwner != PlayerColor::NEUTRAL)
  132. {
  133. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  134. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  135. }
  136. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  137. cb->gameState()->players[PlayerColor(val)].dwellings.emplace_back(this);
  138. }
  139. break;
  140. case ObjProperty::AVAILABLE_CREATURE:
  141. creatures.resize(1);
  142. creatures[0].second.resize(1);
  143. creatures[0].second[0] = CreatureID(val);
  144. break;
  145. }
  146. }
  147. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  148. {
  149. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  150. {
  151. InfoWindow iw;
  152. iw.type = EInfoWindowMode::AUTO;
  153. iw.player = h->tempOwner;
  154. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  155. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  156. cb->sendAndApply(&iw);
  157. return;
  158. }
  159. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  160. if ( relations == PlayerRelations::ALLIES )
  161. return;//do not allow recruiting or capturing
  162. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  163. {
  164. BlockingDialog bd(true,false);
  165. bd.player = h->tempOwner;
  166. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  167. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  168. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  169. bd.text.addReplacement(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  170. else
  171. bd.text.addReplacement(MetaString::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  172. bd.text.addReplacement(*Slots().begin()->second);
  173. cb->showBlockingDialog(&bd);
  174. return;
  175. }
  176. // TODO this shouldn't be hardcoded
  177. if(!relations && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  178. {
  179. cb->setOwner(this, h->tempOwner);
  180. }
  181. BlockingDialog bd (true,false);
  182. bd.player = h->tempOwner;
  183. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  184. {
  185. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  186. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  187. for(const auto & elem : creatures)
  188. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  189. }
  190. else if(ID == Obj::REFUGEE_CAMP)
  191. {
  192. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  193. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  194. for(const auto & elem : creatures)
  195. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  196. }
  197. else if(ID == Obj::WAR_MACHINE_FACTORY)
  198. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  199. else
  200. throw std::runtime_error("Illegal dwelling!");
  201. cb->showBlockingDialog(&bd);
  202. }
  203. void CGDwelling::newTurn(CRandomGenerator & rand) const
  204. {
  205. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  206. return;
  207. //town growths and War Machines Factories are handled separately
  208. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  209. return;
  210. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  211. {
  212. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
  213. }
  214. bool change = false;
  215. SetAvailableCreatures sac;
  216. sac.creatures = creatures;
  217. sac.tid = id;
  218. for (size_t i = 0; i < creatures.size(); i++)
  219. {
  220. if(!creatures[i].second.empty())
  221. {
  222. bool creaturesAccumulate = false;
  223. if (tempOwner.isValidPlayer())
  224. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  225. else
  226. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  227. CCreature *cre = VLC->creh->objects[creatures[i].second[0]];
  228. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  229. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  230. sac.creatures[i].first += amount;
  231. else
  232. sac.creatures[i].first = amount;
  233. change = true;
  234. }
  235. }
  236. if(change)
  237. cb->sendAndApply(&sac);
  238. updateGuards();
  239. }
  240. void CGDwelling::updateGuards() const
  241. {
  242. //TODO: store custom guard config and use it
  243. //TODO: store boolean flag for guards
  244. bool guarded = false;
  245. //default condition - creatures are of level 5 or higher
  246. for (auto creatureEntry : creatures)
  247. {
  248. if (VLC->creatures()->getByIndex(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  249. {
  250. guarded = true;
  251. break;
  252. }
  253. }
  254. if (guarded)
  255. {
  256. for (auto creatureEntry : creatures)
  257. {
  258. const CCreature * crea = VLC->creh->objects[creatureEntry.second.at(0)];
  259. SlotID slot = getSlotFor(crea->getId());
  260. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  261. {
  262. ChangeStackCount csc;
  263. csc.army = this->id;
  264. csc.slot = slot;
  265. csc.count = crea->getGrowth() * 3;
  266. csc.absoluteValue = true;
  267. cb->sendAndApply(&csc);
  268. }
  269. else //slot is empty, create whole new stack
  270. {
  271. InsertNewStack ns;
  272. ns.army = this->id;
  273. ns.slot = slot;
  274. ns.type = crea->getId();
  275. ns.count = crea->getGrowth() * 3;
  276. cb->sendAndApply(&ns);
  277. }
  278. }
  279. }
  280. }
  281. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  282. {
  283. CreatureID crid = creatures[0].second[0];
  284. auto *crs = crid.toCreature();
  285. TQuantity count = creatures[0].first;
  286. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  287. {
  288. if(count) //there are available creatures
  289. {
  290. SlotID slot = h->getSlotFor(crid);
  291. if(!slot.validSlot()) //no available slot
  292. {
  293. InfoWindow iw;
  294. iw.type = EInfoWindowMode::AUTO;
  295. iw.player = h->tempOwner;
  296. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  297. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  298. cb->showInfoDialog(&iw);
  299. }
  300. else //give creatures
  301. {
  302. SetAvailableCreatures sac;
  303. sac.tid = id;
  304. sac.creatures = creatures;
  305. sac.creatures[0].first = 0;
  306. InfoWindow iw;
  307. iw.type = EInfoWindowMode::AUTO;
  308. iw.player = h->tempOwner;
  309. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  310. iw.text.addReplacement(count);
  311. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  312. cb->showInfoDialog(&iw);
  313. cb->sendAndApply(&sac);
  314. cb->addToSlot(StackLocation(h, slot), crs, count);
  315. }
  316. }
  317. else //there no creatures
  318. {
  319. InfoWindow iw;
  320. iw.type = EInfoWindowMode::AUTO;
  321. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  322. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  323. iw.player = h->tempOwner;
  324. cb->sendAndApply(&iw);
  325. }
  326. }
  327. else
  328. {
  329. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  330. {
  331. //there is 1 war machine available to recruit if hero doesn't have one
  332. SetAvailableCreatures sac;
  333. sac.tid = id;
  334. sac.creatures = creatures;
  335. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  336. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  337. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  338. cb->sendAndApply(&sac);
  339. }
  340. OpenWindow ow;
  341. ow.id1 = id.getNum();
  342. ow.id2 = h->id.getNum();
  343. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  344. ? EOpenWindowMode::RECRUITMENT_FIRST
  345. : EOpenWindowMode::RECRUITMENT_ALL;
  346. cb->sendAndApply(&ow);
  347. }
  348. }
  349. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  350. {
  351. if (result.winner == 0)
  352. {
  353. onHeroVisit(hero);
  354. }
  355. }
  356. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  357. {
  358. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  359. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  360. {
  361. if(answer)
  362. cb->startBattleI(hero, this);
  363. }
  364. else if(answer)
  365. {
  366. heroAcceptsCreatures(hero);
  367. }
  368. }
  369. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  370. {
  371. if(!handler.saving)
  372. initRandomObjectInfo();
  373. switch (ID)
  374. {
  375. case Obj::WAR_MACHINE_FACTORY:
  376. case Obj::REFUGEE_CAMP:
  377. //do nothing
  378. break;
  379. case Obj::RANDOM_DWELLING:
  380. case Obj::RANDOM_DWELLING_LVL:
  381. case Obj::RANDOM_DWELLING_FACTION:
  382. info->serializeJson(handler);
  383. //fall through
  384. default:
  385. serializeJsonOwner(handler);
  386. break;
  387. }
  388. }
  389. int CGTownInstance::getSightRadius() const //returns sight distance
  390. {
  391. auto ret = CBuilding::HEIGHT_NO_TOWER;
  392. for(const auto & bid : builtBuildings)
  393. {
  394. if(bid.IsSpecialOrGrail())
  395. {
  396. auto height = town->buildings.at(bid)->height;
  397. if(ret < height)
  398. ret = height;
  399. }
  400. }
  401. return ret;
  402. }
  403. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  404. {
  405. ///this is freakin' overcomplicated solution
  406. switch (what)
  407. {
  408. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  409. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  410. break;
  411. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  412. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  413. break;
  414. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  415. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  416. break;
  417. case ObjProperty::BONUS_VALUE_FIRST:
  418. bonusValue.first = val;
  419. break;
  420. case ObjProperty::BONUS_VALUE_SECOND:
  421. bonusValue.second = val;
  422. break;
  423. }
  424. }
  425. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  426. {
  427. if (hasBuilt(BuildingID::CASTLE))
  428. return CASTLE;
  429. if (hasBuilt(BuildingID::CITADEL))
  430. return CITADEL;
  431. if (hasBuilt(BuildingID::FORT))
  432. return FORT;
  433. return NONE;
  434. }
  435. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  436. {
  437. if (hasBuilt(BuildingID::CAPITOL))
  438. return 3;
  439. if (hasBuilt(BuildingID::CITY_HALL))
  440. return 2;
  441. if (hasBuilt(BuildingID::TOWN_HALL))
  442. return 1;
  443. if (hasBuilt(BuildingID::VILLAGE_HALL))
  444. return 0;
  445. return -1;
  446. }
  447. int CGTownInstance::mageGuildLevel() const
  448. {
  449. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  450. return 5;
  451. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  452. return 4;
  453. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  454. return 3;
  455. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  456. return 2;
  457. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  458. return 1;
  459. return 0;
  460. }
  461. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  462. {
  463. return town->hordeLvl.at(HID);
  464. }
  465. int CGTownInstance::creatureGrowth(const int & level) const
  466. {
  467. return getGrowthInfo(level).totalGrowth();
  468. }
  469. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  470. {
  471. GrowthInfo ret;
  472. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  473. return ret;
  474. if (creatures[level].second.empty())
  475. return ret; //no dwelling
  476. const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
  477. const int base = creature->getGrowth();
  478. int castleBonus = 0;
  479. ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
  480. if (hasBuilt(BuildingID::CASTLE))
  481. ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
  482. else if (hasBuilt(BuildingID::CITADEL))
  483. ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
  484. if(town->hordeLvl.at(0) == level)//horde 1
  485. if(hasBuilt(BuildingID::HORDE_1))
  486. ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
  487. if(town->hordeLvl.at(1) == level)//horde 2
  488. if(hasBuilt(BuildingID::HORDE_2))
  489. ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
  490. //statue-of-legion-like bonus: % to base+castle
  491. TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
  492. for(const auto & b : *bonuses2)
  493. {
  494. const auto growth = b->val * (base + castleBonus) / 100;
  495. ret.entries.emplace_back(growth, b->Description(growth));
  496. }
  497. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  498. TConstBonusListPtr bonuses = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH).And(Selector::subtype()(level)));
  499. for(const auto & b : *bonuses)
  500. ret.entries.emplace_back(b->val, b->Description());
  501. int dwellingBonus = 0;
  502. if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
  503. {
  504. dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
  505. }
  506. if(dwellingBonus)
  507. ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
  508. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  509. ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
  510. return ret;
  511. }
  512. int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
  513. {
  514. int totalBonus = 0;
  515. for (const auto& dwelling : dwellings)
  516. {
  517. for (const auto& creature : dwelling->creatures)
  518. {
  519. totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
  520. }
  521. }
  522. return totalBonus;
  523. }
  524. TResources CGTownInstance::dailyIncome() const
  525. {
  526. TResources ret;
  527. for(const auto & p : town->buildings)
  528. {
  529. BuildingID buildingUpgrade;
  530. for(const auto & p2 : town->buildings)
  531. {
  532. if (p2.second->upgrade == p.first)
  533. {
  534. buildingUpgrade = p2.first;
  535. }
  536. }
  537. if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
  538. {
  539. ret += p.second->produce;
  540. }
  541. }
  542. return ret;
  543. }
  544. bool CGTownInstance::hasFort() const
  545. {
  546. return hasBuilt(BuildingID::FORT);
  547. }
  548. bool CGTownInstance::hasCapitol() const
  549. {
  550. return hasBuilt(BuildingID::CAPITOL);
  551. }
  552. CGTownInstance::CGTownInstance():
  553. IShipyard(this),
  554. IMarket(this),
  555. town(nullptr),
  556. builded(0),
  557. destroyed(0),
  558. identifier(0),
  559. alignment(0xff)
  560. {
  561. this->setNodeType(CBonusSystemNode::TOWN);
  562. }
  563. CGTownInstance::~CGTownInstance()
  564. {
  565. for (auto & elem : bonusingBuildings)
  566. delete elem;
  567. }
  568. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  569. {
  570. if(checkGuild && mageGuildLevel() < level)
  571. return 0;
  572. int ret = 6 - level; //how many spells are available at this level
  573. if (hasBuilt(BuildingSubID::LIBRARY))
  574. ret++;
  575. return ret;
  576. }
  577. bool CGTownInstance::needsLastStack() const
  578. {
  579. return garrisonHero != nullptr;
  580. }
  581. void CGTownInstance::setOwner(const PlayerColor & player) const
  582. {
  583. removeCapitols(player);
  584. cb->setOwner(this, player);
  585. }
  586. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  587. {
  588. if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  589. {
  590. if(armedGarrison() || visitingHero)
  591. {
  592. const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
  593. const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
  594. const bool isBattleOutside = isBattleOutsideTown(defendingHero);
  595. if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
  596. {
  597. //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
  598. auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
  599. if(nodeSiege == (CBonusSystemNode *)this)
  600. cb->swapGarrisonOnSiege(this->id);
  601. const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
  602. }
  603. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
  604. }
  605. else
  606. {
  607. auto heroColor = h->getOwner();
  608. onTownCaptured(heroColor);
  609. if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
  610. {
  611. return; //we just won game, we do not need to perform any extra actions
  612. //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
  613. }
  614. cb->heroVisitCastle(this, h);
  615. }
  616. }
  617. else if(h->visitablePos() == visitablePos())
  618. {
  619. bool commander_recover = h->commander && !h->commander->alive;
  620. if (commander_recover) // rise commander from dead
  621. {
  622. SetCommanderProperty scp;
  623. scp.heroid = h->id;
  624. scp.which = SetCommanderProperty::ALIVE;
  625. scp.amount = 1;
  626. cb->sendAndApply(&scp);
  627. }
  628. cb->heroVisitCastle(this, h);
  629. // TODO(vmarkovtsev): implement payment for rising the commander
  630. if (commander_recover) // info window about commander
  631. {
  632. InfoWindow iw;
  633. iw.player = h->tempOwner;
  634. iw.text << h->commander->getName();
  635. iw.components.emplace_back(*h->commander);
  636. cb->showInfoDialog(&iw);
  637. }
  638. }
  639. else
  640. {
  641. logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), name);
  642. }
  643. }
  644. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  645. {
  646. //FIXME: find out why this issue appears on random maps
  647. if(visitingHero == h)
  648. {
  649. cb->stopHeroVisitCastle(this, h);
  650. logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), name);
  651. }
  652. else
  653. logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), name);
  654. }
  655. std::string CGTownInstance::getObjectName() const
  656. {
  657. return name + ", " + town->faction->getNameTranslated();
  658. }
  659. bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
  660. {
  661. return town->getBuildingType(subId) != BuildingID::NONE;
  662. }
  663. void CGTownInstance::initOverriddenBids()
  664. {
  665. for(const auto & bid : builtBuildings)
  666. {
  667. const auto & overrideThem = town->buildings.at(bid)->overrideBids;
  668. for(const auto & overrideIt : overrideThem)
  669. overriddenBuildings.insert(overrideIt);
  670. }
  671. }
  672. bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
  673. {
  674. auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
  675. {
  676. return building->getBuildingType().num == bid;
  677. });
  678. return present != bonusingBuildings.end();
  679. }
  680. //it does not check hasBuilt because this check is in the OnHeroVisit handler
  681. void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
  682. {
  683. auto bid = town->getBuildingType(subID);
  684. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  685. bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
  686. }
  687. void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
  688. {
  689. auto bid = town->getBuildingType(subID);
  690. if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
  691. bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
  692. }
  693. void CGTownInstance::addTownBonuses()
  694. {
  695. for(const auto & kvp : town->buildings)
  696. {
  697. if(vstd::contains(overriddenBuildings, kvp.first))
  698. continue;
  699. if(kvp.second->IsVisitingBonus())
  700. bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
  701. if(kvp.second->IsWeekBonus())
  702. bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
  703. }
  704. }
  705. DamageRange CGTownInstance::getTowerDamageRange() const
  706. {
  707. assert(hasBuilt(BuildingID::CASTLE));
  708. // http://heroes.thelazy.net/wiki/Arrow_tower
  709. // base damage, irregardless of town level
  710. static constexpr int baseDamage = 6;
  711. // extra damage, for each building in town
  712. static constexpr int extraDamage = 1;
  713. const int minDamage = baseDamage + extraDamage * getTownLevel();
  714. return {
  715. minDamage,
  716. minDamage * 2
  717. };
  718. }
  719. DamageRange CGTownInstance::getKeepDamageRange() const
  720. {
  721. assert(hasBuilt(BuildingID::CITADEL));
  722. // http://heroes.thelazy.net/wiki/Arrow_tower
  723. // base damage, irregardless of town level
  724. static constexpr int baseDamage = 10;
  725. // extra damage, for each building in town
  726. static constexpr int extraDamage = 2;
  727. const int minDamage = baseDamage + extraDamage * getTownLevel();
  728. return {
  729. minDamage,
  730. minDamage * 2
  731. };
  732. }
  733. void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
  734. {
  735. size_t i = 0;
  736. CGTownBuilding * freeIt = nullptr;
  737. for(i = 0; i != bonusingBuildings.size(); i++)
  738. {
  739. if(bonusingBuildings[i]->getBuildingType() == bid)
  740. {
  741. freeIt = bonusingBuildings[i];
  742. break;
  743. }
  744. }
  745. if(freeIt == nullptr)
  746. return;
  747. auto building = town->buildings.at(bid);
  748. auto isVisitingBonus = building->IsVisitingBonus();
  749. auto isWeekBonus = building->IsWeekBonus();
  750. if(!isVisitingBonus && !isWeekBonus)
  751. return;
  752. bonusingBuildings.erase(bonusingBuildings.begin() + i);
  753. delete freeIt;
  754. }
  755. void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
  756. {
  757. blockVisit = true;
  758. if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
  759. creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
  760. else
  761. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  762. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  763. {
  764. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  765. int upgradeNum = 0;
  766. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  767. {
  768. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  769. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  770. }
  771. }
  772. initOverriddenBids();
  773. addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
  774. recreateBuildingsBonuses();
  775. updateAppearance();
  776. }
  777. bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, const BuildingID & bid) const
  778. {
  779. return (this->town->faction != nullptr && this->town->faction->getIndex() == type && hasBuilt(bid));
  780. }
  781. void CGTownInstance::newTurn(CRandomGenerator & rand) const
  782. {
  783. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  784. {
  785. //give resources if there's a Mystic Pond
  786. if (hasBuilt(BuildingSubID::MYSTIC_POND)
  787. && cb->getDate(Date::DAY) != 1
  788. && (tempOwner < PlayerColor::PLAYER_LIMIT)
  789. )
  790. {
  791. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  792. resID = (resID==2)?1:resID;
  793. int resVal = rand.nextInt(1, 4);//with size 1..4
  794. cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
  795. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  796. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  797. }
  798. const auto * manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
  799. if (manaVortex != nullptr)
  800. cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
  801. //get Mana Vortex or Stables bonuses
  802. //same code is in the CGameHandler::buildStructure method
  803. if (visitingHero != nullptr)
  804. cb->visitCastleObjects(this, visitingHero);
  805. if (garrisonHero != nullptr)
  806. cb->visitCastleObjects(this, garrisonHero);
  807. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  808. {
  809. std::vector<SlotID> nativeCrits; //slots
  810. for(const auto & elem : Slots())
  811. {
  812. if (elem.second->type->getFactionIndex() == subID) //native
  813. {
  814. nativeCrits.push_back(elem.first); //collect matching slots
  815. }
  816. }
  817. if(!nativeCrits.empty())
  818. {
  819. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  820. StackLocation sl(this, pos);
  821. const CCreature *c = getCreature(pos);
  822. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  823. {
  824. cb->changeStackCount(sl, c->getGrowth());
  825. }
  826. else //upgrade
  827. {
  828. cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
  829. }
  830. }
  831. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  832. {
  833. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  834. if (!town->creatures[i].empty())
  835. {
  836. CreatureID c = town->creatures[i][0];
  837. SlotID n;
  838. TQuantity count = creatureGrowth(i);
  839. if (!count) // no dwelling
  840. count = VLC->creh->objects[c]->getGrowth();
  841. {//no lower tiers or above current month
  842. if ((n = getSlotFor(c)).validSlot())
  843. {
  844. StackLocation sl(this, n);
  845. if (slotEmpty(n))
  846. cb->insertNewStack(sl, VLC->creh->objects[c], count);
  847. else //add to existing
  848. cb->changeStackCount(sl, count);
  849. }
  850. }
  851. }
  852. }
  853. }
  854. }
  855. }
  856. /*
  857. int3 CGTownInstance::getSightCenter() const
  858. {
  859. return pos - int3(2,0,0);
  860. }
  861. */
  862. bool CGTownInstance::passableFor(PlayerColor color) const
  863. {
  864. if (!armedGarrison())//empty castle - anyone can visit
  865. return true;
  866. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  867. return false;
  868. return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
  869. }
  870. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  871. {
  872. offsets = {int3(-1,2,0), int3(-3,2,0)};
  873. }
  874. void CGTownInstance::mergeGarrisonOnSiege() const
  875. {
  876. auto getWeakestStackSlot = [&](ui64 powerLimit)
  877. {
  878. std::vector<SlotID> weakSlots;
  879. auto stacksList = visitingHero->stacks;
  880. std::pair<SlotID, CStackInstance *> pair;
  881. while(!stacksList.empty())
  882. {
  883. pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
  884. if(powerLimit > pair.second->getPower() &&
  885. (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
  886. {
  887. weakSlots.push_back(pair.first);
  888. stacksList.erase(pair.first);
  889. }
  890. else
  891. break;
  892. }
  893. if(!weakSlots.empty())
  894. return *std::max_element(weakSlots.begin(), weakSlots.end());
  895. return SlotID();
  896. };
  897. auto count = static_cast<int>(stacks.size());
  898. for(int i = 0; i < count; i++)
  899. {
  900. auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
  901. {
  902. ui64 power = elem.second->getPower();
  903. auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
  904. if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
  905. power += visitingHero->getStack(dst).getPower();
  906. return power;
  907. });
  908. auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
  909. if(dst.validSlot())
  910. cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
  911. else
  912. {
  913. dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
  914. if(dst.validSlot())
  915. cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
  916. }
  917. }
  918. }
  919. void CGTownInstance::removeCapitols(const PlayerColor & owner) const
  920. {
  921. if (hasCapitol()) // search if there's an older capitol
  922. {
  923. PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
  924. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  925. {
  926. if (*i != this && (*i)->hasCapitol())
  927. {
  928. RazeStructures rs;
  929. rs.tid = id;
  930. rs.bid.insert(BuildingID::CAPITOL);
  931. rs.destroyed = destroyed;
  932. cb->sendAndApply(&rs);
  933. return;
  934. }
  935. }
  936. }
  937. }
  938. void CGTownInstance::clearArmy() const
  939. {
  940. while(!stacks.empty())
  941. {
  942. cb->eraseStack(StackLocation(this, stacks.begin()->first));
  943. }
  944. }
  945. int CGTownInstance::getBoatType() const
  946. {
  947. switch (town->faction->alignment)
  948. {
  949. case EAlignment::EVIL : return 0;
  950. case EAlignment::GOOD : return 1;
  951. case EAlignment::NEUTRAL : return 2;
  952. }
  953. assert(0);
  954. return -1;
  955. }
  956. int CGTownInstance::getMarketEfficiency() const
  957. {
  958. if(!hasBuiltSomeTradeBuilding())
  959. return 0;
  960. const PlayerState *p = cb->getPlayerState(tempOwner);
  961. assert(p);
  962. int marketCount = 0;
  963. for(const CGTownInstance *t : p->towns)
  964. if(t->hasBuiltSomeTradeBuilding())
  965. marketCount++;
  966. return marketCount;
  967. }
  968. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  969. {
  970. switch(mode)
  971. {
  972. case EMarketMode::RESOURCE_RESOURCE:
  973. case EMarketMode::RESOURCE_PLAYER:
  974. return hasBuilt(BuildingID::MARKETPLACE);
  975. case EMarketMode::ARTIFACT_RESOURCE:
  976. case EMarketMode::RESOURCE_ARTIFACT:
  977. return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
  978. case EMarketMode::CREATURE_RESOURCE:
  979. return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
  980. case EMarketMode::CREATURE_UNDEAD:
  981. return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
  982. case EMarketMode::RESOURCE_SKILL:
  983. return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
  984. default:
  985. assert(0);
  986. return false;
  987. }
  988. }
  989. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  990. {
  991. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  992. {
  993. std::vector<int> ret;
  994. for(const CArtifact *a : merchantArtifacts)
  995. if(a)
  996. ret.push_back(a->getId());
  997. else
  998. ret.push_back(-1);
  999. return ret;
  1000. }
  1001. else if ( mode == EMarketMode::RESOURCE_SKILL )
  1002. {
  1003. return universitySkills;
  1004. }
  1005. else
  1006. return IMarket::availableItemsIds(mode);
  1007. }
  1008. void CGTownInstance::setType(si32 ID, si32 subID)
  1009. {
  1010. assert(ID == Obj::TOWN); // just in case
  1011. CGObjectInstance::setType(ID, subID);
  1012. town = (*VLC->townh)[subID]->town;
  1013. randomizeArmy(subID);
  1014. updateAppearance();
  1015. }
  1016. void CGTownInstance::updateAppearance()
  1017. {
  1018. auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
  1019. //FIXME: not the best way to do this
  1020. auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
  1021. if (app)
  1022. appearance = app;
  1023. }
  1024. std::string CGTownInstance::nodeName() const
  1025. {
  1026. return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + name;
  1027. }
  1028. void CGTownInstance::deserializationFix()
  1029. {
  1030. attachTo(townAndVis);
  1031. //Hero is already handled by CGameState::attachArmedObjects
  1032. // if(visitingHero)
  1033. // visitingHero->attachTo(&townAndVis);
  1034. // if(garrisonHero)
  1035. // garrisonHero->attachTo(this);
  1036. }
  1037. void CGTownInstance::updateMoraleBonusFromArmy()
  1038. {
  1039. auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
  1040. if(!b)
  1041. {
  1042. b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  1043. addNewBonus(b);
  1044. }
  1045. if (garrisonHero)
  1046. {
  1047. b->val = 0;
  1048. CBonusSystemNode::treeHasChanged();
  1049. }
  1050. else
  1051. CArmedInstance::updateMoraleBonusFromArmy();
  1052. }
  1053. void CGTownInstance::recreateBuildingsBonuses()
  1054. {
  1055. BonusList bl;
  1056. getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
  1057. for(const auto & b : bl)
  1058. removeBonus(b);
  1059. for(const auto & bid : builtBuildings)
  1060. {
  1061. if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
  1062. continue;
  1063. auto building = town->buildings.at(bid);
  1064. if(building->buildingBonuses.empty())
  1065. continue;
  1066. for(auto & bonus : building->buildingBonuses)
  1067. {
  1068. if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == ALL_CREATURES)
  1069. VLC->creh->addBonusForAllCreatures(bonus);
  1070. else
  1071. addNewBonus(bonus);
  1072. }
  1073. }
  1074. }
  1075. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  1076. {
  1077. assert(!!visitingHero == !h);
  1078. if(h)
  1079. {
  1080. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1081. assert(p);
  1082. h->detachFrom(*p);
  1083. h->attachTo(townAndVis);
  1084. visitingHero = h;
  1085. h->visitedTown = this;
  1086. h->inTownGarrison = false;
  1087. }
  1088. else
  1089. {
  1090. PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
  1091. visitingHero->visitedTown = nullptr;
  1092. visitingHero->detachFrom(townAndVis);
  1093. visitingHero->attachTo(*p);
  1094. visitingHero = nullptr;
  1095. }
  1096. }
  1097. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  1098. {
  1099. assert(!!garrisonHero == !h);
  1100. if(h)
  1101. {
  1102. PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
  1103. assert(p);
  1104. h->detachFrom(*p);
  1105. h->attachTo(*this);
  1106. garrisonHero = h;
  1107. h->visitedTown = this;
  1108. h->inTownGarrison = true;
  1109. }
  1110. else
  1111. {
  1112. PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
  1113. garrisonHero->visitedTown = nullptr;
  1114. garrisonHero->inTownGarrison = false;
  1115. garrisonHero->detachFrom(*this);
  1116. garrisonHero->attachTo(*p);
  1117. garrisonHero = nullptr;
  1118. }
  1119. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  1120. }
  1121. bool CGTownInstance::armedGarrison() const
  1122. {
  1123. return !stacks.empty() || garrisonHero;
  1124. }
  1125. const CTown * CGTownInstance::getTown() const
  1126. {
  1127. if(ID == Obj::RANDOM_TOWN)
  1128. return VLC->townh->randomTown;
  1129. else
  1130. {
  1131. if(nullptr == town)
  1132. {
  1133. return (*VLC->townh)[subID]->town;
  1134. }
  1135. else
  1136. return town;
  1137. }
  1138. }
  1139. int CGTownInstance::getTownLevel() const
  1140. {
  1141. // count all buildings that are not upgrades
  1142. int level = 0;
  1143. for(const auto & bid : builtBuildings)
  1144. {
  1145. if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
  1146. level++;
  1147. }
  1148. return level;
  1149. }
  1150. CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
  1151. {
  1152. return townAndVis;
  1153. }
  1154. std::string CGTownInstance::getNameTranslated() const
  1155. {
  1156. return name;
  1157. }
  1158. void CGTownInstance::setNameTranslated( const std::string & newName )
  1159. {
  1160. name = newName;
  1161. }
  1162. const CArmedInstance * CGTownInstance::getUpperArmy() const
  1163. {
  1164. if(garrisonHero)
  1165. return garrisonHero;
  1166. return this;
  1167. }
  1168. const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
  1169. {
  1170. for(auto * const building : bonusingBuildings)
  1171. {
  1172. if(building->getBuildingSubtype() == subId)
  1173. return building;
  1174. }
  1175. return nullptr;
  1176. }
  1177. bool CGTownInstance::hasBuiltSomeTradeBuilding() const
  1178. {
  1179. for(const auto & bid : builtBuildings)
  1180. {
  1181. if(town->buildings.at(bid)->IsTradeBuilding())
  1182. return true;
  1183. }
  1184. return false;
  1185. }
  1186. bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
  1187. {
  1188. for(const auto & bid : builtBuildings)
  1189. {
  1190. if(town->buildings.at(bid)->subId == buildingID)
  1191. return true;
  1192. }
  1193. return false;
  1194. }
  1195. bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
  1196. {
  1197. return vstd::contains(builtBuildings, buildingID);
  1198. }
  1199. bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
  1200. {
  1201. if (townID == town->faction->getIndex() || townID == ETownType::ANY)
  1202. return hasBuilt(buildingID);
  1203. return false;
  1204. }
  1205. TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
  1206. {
  1207. if (vstd::contains(town->buildings, buildingID))
  1208. return town->buildings.at(buildingID)->resources;
  1209. else
  1210. {
  1211. logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
  1212. return TResources();
  1213. }
  1214. }
  1215. CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
  1216. {
  1217. const CBuilding * building = town->buildings.at(buildID);
  1218. //TODO: find better solution to prevent infinite loops
  1219. std::set<BuildingID> processed;
  1220. std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
  1221. [&](const BuildingID & id) -> CBuilding::TRequired::Variant
  1222. {
  1223. const CBuilding * build = town->buildings.at(id);
  1224. CBuilding::TRequired::OperatorAll requirements;
  1225. if (!hasBuilt(id))
  1226. {
  1227. if (deep)
  1228. requirements.expressions.emplace_back(id);
  1229. else
  1230. return id;
  1231. }
  1232. if(!vstd::contains(processed, id))
  1233. {
  1234. processed.insert(id);
  1235. if (build->upgrade != BuildingID::NONE)
  1236. requirements.expressions.push_back(dependTest(build->upgrade));
  1237. requirements.expressions.push_back(build->requirements.morph(dependTest));
  1238. }
  1239. return requirements;
  1240. };
  1241. CBuilding::TRequired::OperatorAll requirements;
  1242. if (building->upgrade != BuildingID::NONE)
  1243. {
  1244. const CBuilding * upgr = town->buildings.at(building->upgrade);
  1245. requirements.expressions.push_back(dependTest(upgr->bid));
  1246. processed.clear();
  1247. }
  1248. requirements.expressions.push_back(building->requirements.morph(dependTest));
  1249. CBuilding::TRequired::Variant variant(requirements);
  1250. CBuilding::TRequired ret(variant);
  1251. ret.minimize();
  1252. return ret;
  1253. }
  1254. void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
  1255. {
  1256. if(visitingHero == h)
  1257. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  1258. else if(garrisonHero == h)
  1259. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  1260. else
  1261. {
  1262. //should never ever happen
  1263. logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
  1264. throw std::runtime_error("internal error");
  1265. }
  1266. }
  1267. void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
  1268. {
  1269. if(result.winner == BattleSide::ATTACKER)
  1270. {
  1271. clearArmy();
  1272. onTownCaptured(hero->getOwner());
  1273. }
  1274. }
  1275. void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
  1276. {
  1277. setOwner(winner);
  1278. FoWChange fw;
  1279. fw.player = winner;
  1280. fw.mode = 1;
  1281. cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
  1282. cb->sendAndApply(& fw);
  1283. }
  1284. void CGTownInstance::afterAddToMap(CMap * map)
  1285. {
  1286. if(ID == Obj::TOWN)
  1287. map->towns.emplace_back(this);
  1288. }
  1289. void CGTownInstance::afterRemoveFromMap(CMap * map)
  1290. {
  1291. if (ID == Obj::TOWN)
  1292. vstd::erase_if_present(map->towns, this);
  1293. }
  1294. void CGTownInstance::reset()
  1295. {
  1296. CGTownInstance::merchantArtifacts.clear();
  1297. CGTownInstance::universitySkills.clear();
  1298. }
  1299. void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1300. {
  1301. CGObjectInstance::serializeJsonOwner(handler);
  1302. CCreatureSet::serializeJson(handler, "army", 7);
  1303. handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
  1304. handler.serializeString("name", name);
  1305. {
  1306. auto decodeBuilding = [this](const std::string & identifier) -> si32
  1307. {
  1308. auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
  1309. if(rawId)
  1310. return rawId.get();
  1311. else
  1312. return -1;
  1313. };
  1314. auto encodeBuilding = [this](si32 index) -> std::string
  1315. {
  1316. return getTown()->buildings.at(BuildingID(index))->getJsonKey();
  1317. };
  1318. const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
  1319. JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
  1320. if(handler.saving)
  1321. {
  1322. bool customBuildings = false;
  1323. boost::logic::tribool hasFort(false);
  1324. for(const BuildingID & id : forbiddenBuildings)
  1325. {
  1326. buildingsLIC.none.insert(id);
  1327. customBuildings = true;
  1328. }
  1329. for(const BuildingID & id : builtBuildings)
  1330. {
  1331. if(id == BuildingID::DEFAULT)
  1332. continue;
  1333. const CBuilding * building = getTown()->buildings.at(id);
  1334. if(building->mode == CBuilding::BUILD_AUTO)
  1335. continue;
  1336. if(id == BuildingID::FORT)
  1337. hasFort = true;
  1338. buildingsLIC.all.insert(id);
  1339. customBuildings = true;
  1340. }
  1341. if(customBuildings)
  1342. handler.serializeLIC("buildings", buildingsLIC);
  1343. else
  1344. handler.serializeBool("hasFort",hasFort);
  1345. }
  1346. else
  1347. {
  1348. handler.serializeLIC("buildings", buildingsLIC);
  1349. builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1350. if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
  1351. {
  1352. builtBuildings.insert(BuildingID::DEFAULT);
  1353. bool hasFort = false;
  1354. handler.serializeBool("hasFort",hasFort);
  1355. if(hasFort)
  1356. builtBuildings.insert(BuildingID::FORT);
  1357. }
  1358. else
  1359. {
  1360. for(const si32 item : buildingsLIC.none)
  1361. forbiddenBuildings.insert(BuildingID(item));
  1362. for(const si32 item : buildingsLIC.all)
  1363. builtBuildings.insert(BuildingID(item));
  1364. }
  1365. }
  1366. }
  1367. {
  1368. std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
  1369. JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
  1370. if(handler.saving)
  1371. {
  1372. for(const SpellID & id : possibleSpells)
  1373. spellsLIC.any[id.num] = true;
  1374. for(const SpellID & id : obligatorySpells)
  1375. spellsLIC.all[id.num] = true;
  1376. }
  1377. handler.serializeLIC("spells", spellsLIC);
  1378. if(!handler.saving)
  1379. {
  1380. possibleSpells.clear();
  1381. for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
  1382. {
  1383. if(spellsLIC.any[idx])
  1384. possibleSpells.emplace_back(idx);
  1385. }
  1386. obligatorySpells.clear();
  1387. for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
  1388. {
  1389. if(spellsLIC.all[idx])
  1390. obligatorySpells.emplace_back(idx);
  1391. }
  1392. }
  1393. }
  1394. }
  1395. PlayerColor CGTownBuilding::getOwner() const
  1396. {
  1397. return town->getOwner();
  1398. }
  1399. int32_t CGTownBuilding::getObjGroupIndex() const
  1400. {
  1401. return -1;
  1402. }
  1403. int32_t CGTownBuilding::getObjTypeIndex() const
  1404. {
  1405. return 0;
  1406. }
  1407. int3 CGTownBuilding::visitablePos() const
  1408. {
  1409. return town->visitablePos();
  1410. }
  1411. int3 CGTownBuilding::getPosition() const
  1412. {
  1413. return town->getPosition();
  1414. }
  1415. COPWBonus::COPWBonus(const BuildingID & bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1416. {
  1417. bID = bid;
  1418. bType = subId;
  1419. town = cgTown;
  1420. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1421. }
  1422. void COPWBonus::setProperty(ui8 what, ui32 val)
  1423. {
  1424. switch (what)
  1425. {
  1426. case ObjProperty::VISITORS:
  1427. visitors.insert(val);
  1428. break;
  1429. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1430. visitors.clear();
  1431. break;
  1432. }
  1433. }
  1434. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  1435. {
  1436. ObjectInstanceID heroID = h->id;
  1437. if(town->hasBuilt(bID))
  1438. {
  1439. InfoWindow iw;
  1440. iw.player = h->tempOwner;
  1441. switch (this->bType)
  1442. {
  1443. case BuildingSubID::STABLES:
  1444. if(!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  1445. {
  1446. GiveBonus gb;
  1447. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100], 1);
  1448. gb.id = heroID.getNum();
  1449. cb->giveHeroBonus(&gb);
  1450. SetMovePoints mp;
  1451. mp.val = 600;
  1452. mp.absolute = false;
  1453. mp.hid = heroID;
  1454. cb->setMovePoints(&mp);
  1455. iw.text << VLC->generaltexth->allTexts[580];
  1456. cb->showInfoDialog(&iw);
  1457. }
  1458. break;
  1459. case BuildingSubID::MANA_VORTEX:
  1460. if(visitors.empty())
  1461. {
  1462. if(h->mana < h->manaLimit() * 2)
  1463. cb->setManaPoints (heroID, 2 * h->manaLimit());
  1464. //TODO: investigate line below
  1465. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  1466. iw.text << getVisitingBonusGreeting();
  1467. cb->showInfoDialog(&iw);
  1468. //extra visit penalty if hero alredy had double mana points (or even more?!)
  1469. town->addHeroToStructureVisitors(h, indexOnTV);
  1470. }
  1471. break;
  1472. }
  1473. }
  1474. }
  1475. CTownBonus::CTownBonus(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
  1476. {
  1477. bID = index;
  1478. bType = subId;
  1479. town = cgTown;
  1480. indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
  1481. }
  1482. void CTownBonus::setProperty (ui8 what, ui32 val)
  1483. {
  1484. if(what == ObjProperty::VISITORS)
  1485. visitors.insert(ObjectInstanceID(val));
  1486. }
  1487. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  1488. {
  1489. ObjectInstanceID heroID = h->id;
  1490. if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
  1491. {
  1492. si64 val = 0;
  1493. InfoWindow iw;
  1494. PrimarySkill::PrimarySkill what = PrimarySkill::NONE;
  1495. switch(bType)
  1496. {
  1497. case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
  1498. what = PrimarySkill::KNOWLEDGE;
  1499. val = 1;
  1500. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 3, 1, 0);
  1501. break;
  1502. case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
  1503. what = PrimarySkill::SPELL_POWER;
  1504. val = 1;
  1505. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 2, 1, 0);
  1506. break;
  1507. case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
  1508. what = PrimarySkill::ATTACK;
  1509. val = 1;
  1510. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 0, 1, 0);
  1511. break;
  1512. case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
  1513. what = PrimarySkill::EXPERIENCE;
  1514. val = static_cast<int>(h->calculateXp(1000));
  1515. iw.components.emplace_back(Component::EComponentType::EXPERIENCE, 0, val, 0);
  1516. break;
  1517. case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
  1518. what = PrimarySkill::DEFENSE;
  1519. val = 1;
  1520. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, 1, 1, 0);
  1521. break;
  1522. case BuildingSubID::CUSTOM_VISITING_BONUS:
  1523. const auto building = town->town->buildings.at(bID);
  1524. if(!h->hasBonusFrom(Bonus::TOWN_STRUCTURE, Bonus::getSid32(building->town->faction->getIndex(), building->bid)))
  1525. {
  1526. const auto & bonuses = building->onVisitBonuses;
  1527. applyBonuses(const_cast<CGHeroInstance *>(h), bonuses);
  1528. }
  1529. break;
  1530. }
  1531. if(what != PrimarySkill::NONE)
  1532. {
  1533. iw.player = cb->getOwner(heroID);
  1534. iw.text << getVisitingBonusGreeting();
  1535. cb->showInfoDialog(&iw);
  1536. cb->changePrimSkill (cb->getHero(heroID), what, val);
  1537. town->addHeroToStructureVisitors(h, indexOnTV);
  1538. }
  1539. }
  1540. }
  1541. void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const
  1542. {
  1543. auto addToVisitors = false;
  1544. for(const auto & bonus : bonuses)
  1545. {
  1546. GiveBonus gb;
  1547. InfoWindow iw;
  1548. if(bonus->type == Bonus::TOWN_MAGIC_WELL)
  1549. {
  1550. if(h->mana >= h->manaLimit())
  1551. return;
  1552. cb->setManaPoints(h->id, h->manaLimit());
  1553. bonus->duration = Bonus::ONE_DAY;
  1554. }
  1555. gb.bonus = * bonus;
  1556. gb.id = h->id.getNum();
  1557. cb->giveHeroBonus(&gb);
  1558. if(bonus->duration == Bonus::PERMANENT)
  1559. addToVisitors = true;
  1560. iw.player = cb->getOwner(h->id);
  1561. iw.text << getCustomBonusGreeting(gb.bonus);
  1562. cb->showInfoDialog(&iw);
  1563. }
  1564. if(addToVisitors)
  1565. town->addHeroToStructureVisitors(h, indexOnTV);
  1566. }
  1567. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  1568. : count(_count)
  1569. {
  1570. description = boost::str(boost::format(format) % count);
  1571. }
  1572. GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
  1573. {
  1574. description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
  1575. }
  1576. GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
  1577. count(_count),
  1578. description(std::move(fullDescription))
  1579. {
  1580. }
  1581. CTownAndVisitingHero::CTownAndVisitingHero()
  1582. {
  1583. setNodeType(TOWN_AND_VISITOR);
  1584. }
  1585. int GrowthInfo::totalGrowth() const
  1586. {
  1587. int ret = 0;
  1588. for(const Entry &entry : entries)
  1589. ret += entry.count;
  1590. return ret;
  1591. }
  1592. std::string CGTownBuilding::getVisitingBonusGreeting() const
  1593. {
  1594. auto bonusGreeting = town->town->getGreeting(bType);
  1595. if(!bonusGreeting.empty())
  1596. return bonusGreeting;
  1597. switch(bType)
  1598. {
  1599. case BuildingSubID::MANA_VORTEX:
  1600. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingManaVortex"));
  1601. break;
  1602. case BuildingSubID::KNOWLEDGE_VISITING_BONUS:
  1603. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingKnowledge"));
  1604. break;
  1605. case BuildingSubID::SPELL_POWER_VISITING_BONUS:
  1606. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingSpellPower"));
  1607. break;
  1608. case BuildingSubID::ATTACK_VISITING_BONUS:
  1609. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingAttack"));
  1610. break;
  1611. case BuildingSubID::EXPERIENCE_VISITING_BONUS:
  1612. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingExperience"));
  1613. break;
  1614. case BuildingSubID::DEFENSE_VISITING_BONUS:
  1615. bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingDefence"));
  1616. break;
  1617. }
  1618. auto buildingName = town->town->getSpecialBuilding(bType)->getNameTranslated();
  1619. if(bonusGreeting.empty())
  1620. {
  1621. bonusGreeting = "Error: Bonus greeting for '%s' is not localized.";
  1622. logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->town->faction->getNameTranslated());
  1623. }
  1624. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1625. town->town->setGreeting(bType, bonusGreeting);
  1626. return bonusGreeting;
  1627. }
  1628. std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const
  1629. {
  1630. if(bonus.type == Bonus::TOWN_MAGIC_WELL)
  1631. {
  1632. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingInTownMagicWell"));
  1633. auto buildingName = town->town->getSpecialBuilding(bType)->getNameTranslated();
  1634. boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
  1635. return bonusGreeting;
  1636. }
  1637. auto bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingCustomBonus")); //"%s gives you +%d %s%s"
  1638. std::string param;
  1639. std::string until;
  1640. if(bonus.type == Bonus::MORALE)
  1641. param = VLC->generaltexth->allTexts[384];
  1642. else if(bonus.type == Bonus::LUCK)
  1643. param = VLC->generaltexth->allTexts[385];
  1644. until = bonus.duration == static_cast<ui16>(Bonus::ONE_BATTLE)
  1645. ? VLC->generaltexth->translate("vcmi.townHall.greetingCustomUntil")
  1646. : ".";
  1647. boost::format fmt = boost::format(bonusGreeting) % bonus.description % bonus.val % param % until;
  1648. std::string greeting = fmt.str();
  1649. return greeting;
  1650. }
  1651. VCMI_LIB_NAMESPACE_END