2
0

CGTownInstance.cpp 36 KB

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