CGDwelling.cpp 16 KB

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