CGDwelling.cpp 16 KB

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