CGTownInstance.cpp 46 KB

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