CGDwelling.cpp 16 KB

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