CGTownInstance.cpp 44 KB

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