CGTownInstance.cpp 39 KB

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