2
0

CGTownInstance.cpp 43 KB

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