CGDwelling.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /*
  2. * CGDwelling.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 "CGDwelling.h"
  12. #include "../callback/IGameInfoCallback.h"
  13. #include "../callback/IGameEventCallback.h"
  14. #include "../serializer/JsonSerializeFormat.h"
  15. #include "../entities/faction/CTownHandler.h"
  16. #include "../mapping/CMap.h"
  17. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  18. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  19. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../mapObjects/CGTownInstance.h"
  22. #include "../networkPacks/StackLocation.h"
  23. #include "../networkPacks/PacksForClient.h"
  24. #include "../networkPacks/PacksForClientBattle.h"
  25. #include "../gameState/CGameState.h"
  26. #include "../CPlayerState.h"
  27. #include "../IGameSettings.h"
  28. #include "../CConfigHandler.h"
  29. #include <vstd/RNG.h>
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. void CGDwellingRandomizationInfo::serializeJson(JsonSerializeFormat & handler)
  32. {
  33. handler.serializeString("sameAsTown", instanceId);
  34. handler.serializeIdArray("allowedFactions", allowedFactions);
  35. handler.serializeInt("minLevel", minLevel, static_cast<uint8_t>(1));
  36. handler.serializeInt("maxLevel", maxLevel, static_cast<uint8_t>(7));
  37. if(!handler.saving)
  38. {
  39. //todo: safely allow any level > 7
  40. vstd::abetween<uint8_t>(minLevel, 1, 7);
  41. vstd::abetween<uint8_t>(maxLevel, minLevel, 7);
  42. }
  43. }
  44. CGDwelling::CGDwelling(IGameInfoCallback *cb):
  45. CArmedInstance(cb)
  46. {}
  47. CGDwelling::~CGDwelling() = default;
  48. FactionID CGDwelling::randomizeFaction(vstd::RNG & rand)
  49. {
  50. if (ID == Obj::RANDOM_DWELLING_FACTION)
  51. return FactionID(subID.getNum());
  52. assert(ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_LVL);
  53. assert(randomizationInfo.has_value());
  54. if (!randomizationInfo)
  55. return FactionID::CASTLE;
  56. CGTownInstance * linkedTown = nullptr;
  57. if (!randomizationInfo->instanceId.empty())
  58. {
  59. auto iter = cb->gameState().getMap().instanceNames.find(randomizationInfo->instanceId);
  60. if(iter == cb->gameState().getMap().instanceNames.end())
  61. logGlobal->error("Map object not found: %s", randomizationInfo->instanceId);
  62. linkedTown = dynamic_cast<CGTownInstance *>(iter->second.get());
  63. }
  64. if (randomizationInfo->identifier != 0)
  65. {
  66. for(auto & townID : cb->gameState().getMap().getAllTowns())
  67. {
  68. auto town = cb->gameState().getTown(townID);
  69. if(town && town->identifier == randomizationInfo->identifier)
  70. {
  71. linkedTown = town;
  72. break;
  73. }
  74. }
  75. }
  76. if (linkedTown)
  77. {
  78. if(linkedTown->ID==Obj::RANDOM_TOWN)
  79. linkedTown->pickRandomObject(rand); //we have to randomize the castle first
  80. assert(linkedTown->ID == Obj::TOWN);
  81. if(linkedTown->ID==Obj::TOWN)
  82. return linkedTown->getFactionID();
  83. }
  84. if(!randomizationInfo->allowedFactions.empty())
  85. return *RandomGeneratorUtil::nextItem(randomizationInfo->allowedFactions, rand);
  86. std::vector<FactionID> potentialPicks;
  87. for (FactionID faction(0); faction < FactionID(LIBRARY->townh->size()); ++faction)
  88. if (LIBRARY->factions()->getById(faction)->hasTown())
  89. potentialPicks.push_back(faction);
  90. assert(!potentialPicks.empty());
  91. return *RandomGeneratorUtil::nextItem(potentialPicks, rand);
  92. }
  93. int CGDwelling::randomizeLevel(vstd::RNG & rand)
  94. {
  95. if (ID == Obj::RANDOM_DWELLING_LVL)
  96. return subID.getNum();
  97. assert(ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_FACTION);
  98. assert(randomizationInfo.has_value());
  99. if (!randomizationInfo)
  100. return rand.nextInt(1, 7) - 1;
  101. if(randomizationInfo->minLevel == randomizationInfo->maxLevel)
  102. return randomizationInfo->minLevel - 1;
  103. return rand.nextInt(randomizationInfo->minLevel, randomizationInfo->maxLevel) - 1;
  104. }
  105. void CGDwelling::pickRandomObject(vstd::RNG & rand)
  106. {
  107. if (ID == Obj::RANDOM_DWELLING || ID == Obj::RANDOM_DWELLING_LVL || ID == Obj::RANDOM_DWELLING_FACTION)
  108. {
  109. FactionID faction = randomizeFaction(rand);
  110. int level = randomizeLevel(rand);
  111. assert(faction != FactionID::NONE && faction != FactionID::NEUTRAL);
  112. assert(level >= 0 && level <= 6);
  113. randomizationInfo.reset();
  114. CreatureID cid = (*LIBRARY->townh)[faction]->town->creatures[level][0];
  115. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  116. //check for block map equality is better but more complex solution
  117. auto testID = [&](const Obj & primaryID) -> MapObjectSubID
  118. {
  119. auto dwellingIDs = LIBRARY->objtypeh->knownSubObjects(primaryID);
  120. for (MapObjectSubID entry : dwellingIDs)
  121. {
  122. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(LIBRARY->objtypeh->getHandlerFor(primaryID, entry).get());
  123. if (!handler->isBannedForRandomDwelling() && handler->producesCreature(cid.toCreature()))
  124. return MapObjectSubID(entry);
  125. }
  126. return MapObjectSubID();
  127. };
  128. ID = Obj::CREATURE_GENERATOR1;
  129. subID = testID(Obj::CREATURE_GENERATOR1);
  130. if (subID == MapObjectSubID())
  131. {
  132. ID = Obj::CREATURE_GENERATOR4;
  133. subID = testID(Obj::CREATURE_GENERATOR4);
  134. }
  135. if (subID == MapObjectSubID())
  136. {
  137. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*LIBRARY->townh)[faction]->getNameTranslated(), int(level));
  138. ID = Obj::CREATURE_GENERATOR1;
  139. subID = *RandomGeneratorUtil::nextItem(LIBRARY->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), rand);
  140. }
  141. setType(ID, subID);
  142. }
  143. }
  144. void CGDwelling::initObj(vstd::RNG & rand)
  145. {
  146. switch(ID.toEnum())
  147. {
  148. case Obj::CREATURE_GENERATOR1:
  149. case Obj::CREATURE_GENERATOR4:
  150. case Obj::WAR_MACHINE_FACTORY:
  151. {
  152. getObjectHandler()->configureObject(this, rand);
  153. assert(!creatures.empty());
  154. assert(!creatures[0].second.empty());
  155. break;
  156. }
  157. case Obj::REFUGEE_CAMP:
  158. //is handled within newturn func
  159. break;
  160. default:
  161. assert(0);
  162. break;
  163. }
  164. }
  165. void CGDwelling::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  166. {
  167. switch (what)
  168. {
  169. case ObjProperty::AVAILABLE_CREATURE:
  170. creatures.resize(1);
  171. creatures[0].second.resize(1);
  172. creatures[0].second[0] = identifier.as<CreatureID>();
  173. break;
  174. }
  175. }
  176. void CGDwelling::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  177. {
  178. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  179. {
  180. InfoWindow iw;
  181. iw.type = EInfoWindowMode::AUTO;
  182. iw.player = h->tempOwner;
  183. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  184. iw.text.replaceName(ID, subID);
  185. gameEvents.sendAndApply(iw);
  186. return;
  187. }
  188. PlayerRelations relations = cb->getPlayerRelations( h->tempOwner, tempOwner );
  189. if ( relations == PlayerRelations::ALLIES )
  190. return;//do not allow recruiting or capturing
  191. if(relations == PlayerRelations::ENEMIES && stacksCount() > 0) //object is guarded, owned by enemy
  192. {
  193. BlockingDialog bd(true,false);
  194. bd.player = h->tempOwner;
  195. bd.text.appendLocalString(EMetaText::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  196. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  197. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  198. bd.text.replaceRawString(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  199. else
  200. bd.text.replaceLocalString(EMetaText::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  201. bd.text.replaceName(*Slots().begin()->second);
  202. gameEvents.showBlockingDialog(this, &bd);
  203. return;
  204. }
  205. // TODO this shouldn't be hardcoded
  206. if(relations == PlayerRelations::ENEMIES && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  207. {
  208. gameEvents.setOwner(this, h->tempOwner);
  209. }
  210. BlockingDialog bd (true,false);
  211. bd.player = h->tempOwner;
  212. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  213. {
  214. bd.text.appendLocalString(EMetaText::ADVOB_TXT, creatures.size() == 1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  215. bd.text.replaceTextID(getObjectHandler()->getNameTextID());
  216. for(const auto & elem : creatures)
  217. bd.text.replaceNamePlural(elem.second[0]);
  218. }
  219. else if(ID == Obj::REFUGEE_CAMP)
  220. {
  221. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  222. bd.text.replaceName(ID, subID);
  223. for(const auto & elem : creatures)
  224. bd.text.replaceNamePlural(elem.second[0]);
  225. }
  226. else if(ID == Obj::WAR_MACHINE_FACTORY)
  227. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  228. else
  229. throw std::runtime_error("Illegal dwelling!");
  230. if(ID == Obj::REFUGEE_CAMP || (ID == Obj::CREATURE_GENERATOR1 && LIBRARY->creatures()->getById(creatures[0].second[0])->getLevel() != 1))
  231. {
  232. bd.flags |= BlockingDialog::SAFE_TO_AUTOACCEPT;
  233. }
  234. gameEvents.showBlockingDialog(this, &bd);
  235. }
  236. void CGDwelling::newTurn(IGameEventCallback & gameEvents) const
  237. {
  238. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  239. return;
  240. //town growths and War Machines Factories are handled separately
  241. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  242. return;
  243. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  244. {
  245. gameEvents.setObjPropertyID(id, ObjProperty::AVAILABLE_CREATURE, LIBRARY->creh->pickRandomMonster(gameEvents.getRandomGenerator()));
  246. }
  247. bool change = false;
  248. SetAvailableCreatures sac;
  249. sac.creatures = creatures;
  250. sac.tid = id;
  251. for (size_t i = 0; i < creatures.size(); i++)
  252. {
  253. if(!creatures[i].second.empty())
  254. {
  255. bool creaturesAccumulate = false;
  256. if (tempOwner.isValidPlayer())
  257. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  258. else
  259. creaturesAccumulate = cb->getSettings().getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  260. const CCreature * cre =creatures[i].second[0].toCreature();
  261. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(BonusType::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(cre->getLevel()));
  262. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  263. sac.creatures[i].first += amount;
  264. else
  265. sac.creatures[i].first = amount;
  266. change = true;
  267. }
  268. }
  269. if(change)
  270. gameEvents.sendAndApply(sac);
  271. updateGuards(gameEvents);
  272. }
  273. std::vector<Component> CGDwelling::getPopupComponents(PlayerColor player) const
  274. {
  275. bool visitedByOwner = getOwner() == player;
  276. std::vector<Component> result;
  277. if (ID == Obj::CREATURE_GENERATOR1 && !creatures.empty())
  278. {
  279. for (auto const & creature : creatures.front().second)
  280. {
  281. if (visitedByOwner)
  282. result.emplace_back(ComponentType::CREATURE, creature, creatures.front().first);
  283. else
  284. result.emplace_back(ComponentType::CREATURE, creature);
  285. }
  286. }
  287. if (ID == Obj::CREATURE_GENERATOR4)
  288. {
  289. for (auto const & creatureLevel : creatures)
  290. {
  291. if (!creatureLevel.second.empty())
  292. {
  293. if (visitedByOwner)
  294. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back(), creatureLevel.first);
  295. else
  296. result.emplace_back(ComponentType::CREATURE, creatureLevel.second.back());
  297. }
  298. }
  299. }
  300. return result;
  301. }
  302. void CGDwelling::updateGuards(IGameEventCallback & gameEvents) const
  303. {
  304. //TODO: store custom guard config and use it
  305. //TODO: store boolean flag for guards
  306. bool guarded = false;
  307. //default condition - creatures are of level 5 or higher
  308. for (auto creatureEntry : creatures)
  309. {
  310. if (LIBRARY->creatures()->getById(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  311. {
  312. guarded = true;
  313. break;
  314. }
  315. }
  316. if (guarded)
  317. {
  318. for (auto creatureEntry : creatures)
  319. {
  320. const CCreature * crea = creatureEntry.second.at(0).toCreature();
  321. SlotID slot = getSlotFor(crea->getId());
  322. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  323. {
  324. ChangeStackCount csc;
  325. csc.army = this->id;
  326. csc.slot = slot;
  327. csc.count = crea->getGrowth() * 3;
  328. csc.mode = ChangeValueMode::ABSOLUTE;
  329. gameEvents.sendAndApply(csc);
  330. }
  331. else //slot is empty, create whole new stack
  332. {
  333. InsertNewStack ns;
  334. ns.army = this->id;
  335. ns.slot = slot;
  336. ns.type = crea->getId();
  337. ns.count = crea->getGrowth() * 3;
  338. gameEvents.sendAndApply(ns);
  339. }
  340. }
  341. }
  342. }
  343. void CGDwelling::heroAcceptsCreatures(IGameEventCallback & gameEvents, const CGHeroInstance *h) const
  344. {
  345. CreatureID crid = creatures[0].second[0];
  346. auto *crs = crid.toCreature();
  347. TQuantity count = creatures[0].first;
  348. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  349. {
  350. if(count) //there are available creatures
  351. {
  352. if (cb->getSettings().getBoolean(EGameSettings::DWELLINGS_MERGE_ON_RECRUIT))
  353. {
  354. SlotID testSlot = h->getSlotFor(crid);
  355. if(!testSlot.validSlot()) //no available slot - try merging army of visiting hero
  356. {
  357. std::pair<SlotID, SlotID> toMerge;
  358. if (h->mergeableStacks(toMerge))
  359. {
  360. gameEvents.moveStack(StackLocation(h->id, toMerge.first), StackLocation(h->id, toMerge.second), -1); //merge toMerge.first into toMerge.second
  361. assert(!h->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  362. }
  363. }
  364. }
  365. SlotID slot = h->getSlotFor(crid);
  366. if(!slot.validSlot()) //no available slot
  367. {
  368. InfoWindow iw;
  369. iw.type = EInfoWindowMode::AUTO;
  370. iw.player = h->tempOwner;
  371. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  372. iw.text.replaceNamePlural(crid);
  373. gameEvents.showInfoDialog(&iw);
  374. }
  375. else //give creatures
  376. {
  377. SetAvailableCreatures sac;
  378. sac.tid = id;
  379. sac.creatures = creatures;
  380. sac.creatures[0].first = 0;
  381. InfoWindow iw;
  382. iw.type = EInfoWindowMode::AUTO;
  383. iw.player = h->tempOwner;
  384. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 423); //%d %s join your army.
  385. iw.text.replaceNumber(count);
  386. iw.text.replaceNamePlural(crid);
  387. gameEvents.showInfoDialog(&iw);
  388. gameEvents.sendAndApply(sac);
  389. gameEvents.addToSlot(StackLocation(h->id, slot), crs, count);
  390. }
  391. }
  392. else //there no creatures
  393. {
  394. InfoWindow iw;
  395. iw.type = EInfoWindowMode::AUTO;
  396. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 422); //There are no %s here to recruit.
  397. iw.text.replaceNamePlural(crid);
  398. iw.player = h->tempOwner;
  399. gameEvents.sendAndApply(iw);
  400. }
  401. }
  402. else
  403. {
  404. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  405. {
  406. //there is 1 war machine available to recruit if hero doesn't have one
  407. SetAvailableCreatures sac;
  408. sac.tid = id;
  409. sac.creatures = creatures;
  410. for (auto & entry : sac.creatures)
  411. {
  412. CreatureID creature = entry.second.at(0);
  413. ArtifactID warMachine = creature.toCreature()->warMachine;
  414. if (h->hasArt(warMachine, true, false))
  415. entry.first = 0;
  416. else
  417. entry.first = 1;
  418. }
  419. gameEvents.sendAndApply(sac);
  420. }
  421. auto windowMode = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP) ? EOpenWindowMode::RECRUITMENT_FIRST : EOpenWindowMode::RECRUITMENT_ALL;
  422. gameEvents.showObjectWindow(this, windowMode, h, true);
  423. }
  424. }
  425. void CGDwelling::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance *hero, const BattleResult &result) const
  426. {
  427. if (result.winner == BattleSide::ATTACKER)
  428. {
  429. onHeroVisit(gameEvents, hero);
  430. }
  431. }
  432. void CGDwelling::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  433. {
  434. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  435. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  436. {
  437. if(answer)
  438. gameEvents.startBattle(hero, this);
  439. }
  440. else if(answer)
  441. {
  442. heroAcceptsCreatures(gameEvents, hero);
  443. }
  444. }
  445. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  446. {
  447. switch (ID.toEnum())
  448. {
  449. case Obj::WAR_MACHINE_FACTORY:
  450. case Obj::REFUGEE_CAMP:
  451. //do nothing
  452. break;
  453. case Obj::RANDOM_DWELLING:
  454. case Obj::RANDOM_DWELLING_LVL:
  455. case Obj::RANDOM_DWELLING_FACTION:
  456. if (!handler.saving)
  457. randomizationInfo = CGDwellingRandomizationInfo();
  458. randomizationInfo->serializeJson(handler);
  459. [[fallthrough]];
  460. default:
  461. serializeJsonOwner(handler);
  462. break;
  463. }
  464. }
  465. const IOwnableObject * CGDwelling::asOwnable() const
  466. {
  467. switch (ID.toEnum())
  468. {
  469. case Obj::WAR_MACHINE_FACTORY:
  470. case Obj::REFUGEE_CAMP:
  471. return nullptr; // can't be owned
  472. default:
  473. return this;
  474. }
  475. }
  476. ResourceSet CGDwelling::dailyIncome() const
  477. {
  478. return {};
  479. }
  480. std::vector<CreatureID> CGDwelling::providedCreatures() const
  481. {
  482. if (ID == Obj::WAR_MACHINE_FACTORY || ID == Obj::REFUGEE_CAMP)
  483. return {};
  484. std::vector<CreatureID> result;
  485. for (const auto & level : creatures)
  486. result.insert(result.end(), level.second.begin(), level.second.end());
  487. return result;
  488. }
  489. VCMI_LIB_NAMESPACE_END