CGTownInstance.cpp 51 KB

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