CGTownInstance.cpp 44 KB

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