CGDwelling.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 < 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 >= 1 && level <= 7);
  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(VLC->creh->objects[cid]))
  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. }
  137. }
  138. void CGDwelling::initObj(CRandomGenerator & rand)
  139. {
  140. switch(ID)
  141. {
  142. case Obj::CREATURE_GENERATOR1:
  143. case Obj::CREATURE_GENERATOR4:
  144. {
  145. getObjectHandler()->configureObject(this, rand);
  146. if (getOwner() != PlayerColor::NEUTRAL)
  147. cb->gameState()->players[getOwner()].dwellings.emplace_back(this);
  148. assert(!creatures.empty());
  149. assert(!creatures[0].second.empty());
  150. break;
  151. }
  152. case Obj::REFUGEE_CAMP:
  153. //is handled within newturn func
  154. break;
  155. case Obj::WAR_MACHINE_FACTORY:
  156. creatures.resize(3);
  157. creatures[0].second.emplace_back(CreatureID::BALLISTA);
  158. creatures[1].second.emplace_back(CreatureID::FIRST_AID_TENT);
  159. creatures[2].second.emplace_back(CreatureID::AMMO_CART);
  160. break;
  161. default:
  162. assert(0);
  163. break;
  164. }
  165. }
  166. void CGDwelling::setPropertyDer(ui8 what, ui32 val)
  167. {
  168. switch (what)
  169. {
  170. case ObjProperty::OWNER: //change owner
  171. if (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR2
  172. || ID == Obj::CREATURE_GENERATOR3 || ID == Obj::CREATURE_GENERATOR4)
  173. {
  174. if (tempOwner != PlayerColor::NEUTRAL)
  175. {
  176. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  177. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  178. }
  179. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  180. cb->gameState()->players[PlayerColor(val)].dwellings.emplace_back(this);
  181. }
  182. break;
  183. case ObjProperty::AVAILABLE_CREATURE:
  184. creatures.resize(1);
  185. creatures[0].second.resize(1);
  186. creatures[0].second[0] = CreatureID(val);
  187. break;
  188. }
  189. }
  190. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  191. {
  192. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  193. {
  194. InfoWindow iw;
  195. iw.type = EInfoWindowMode::AUTO;
  196. iw.player = h->tempOwner;
  197. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  198. iw.text.replaceLocalString(EMetaText::OBJ_NAMES, ID);
  199. cb->sendAndApply(&iw);
  200. return;
  201. }
  202. PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  203. if ( relations == PlayerRelations::ALLIES )
  204. return;//do not allow recruiting or capturing
  205. if(relations == PlayerRelations::ENEMIES && stacksCount() > 0) //object is guarded, owned by enemy
  206. {
  207. BlockingDialog bd(true,false);
  208. bd.player = h->tempOwner;
  209. 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?
  210. bd.text.replaceLocalString(ID == Obj::CREATURE_GENERATOR1 ? EMetaText::CREGENS : EMetaText::CREGENS4, subID);
  211. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  212. bd.text.replaceRawString(CCreature::getQuantityRangeStringForId(Slots().begin()->second->getQuantityID()));
  213. else
  214. bd.text.replaceLocalString(EMetaText::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
  215. bd.text.replaceCreatureName(*Slots().begin()->second);
  216. cb->showBlockingDialog(&bd);
  217. return;
  218. }
  219. // TODO this shouldn't be hardcoded
  220. if(relations == PlayerRelations::ENEMIES && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
  221. {
  222. cb->setOwner(this, h->tempOwner);
  223. }
  224. BlockingDialog bd (true,false);
  225. bd.player = h->tempOwner;
  226. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  227. {
  228. 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?
  229. bd.text.replaceLocalString(ID == Obj::CREATURE_GENERATOR1 ? EMetaText::CREGENS : EMetaText::CREGENS4, subID);
  230. for(const auto & elem : creatures)
  231. bd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, elem.second[0]);
  232. }
  233. else if(ID == Obj::REFUGEE_CAMP)
  234. {
  235. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  236. bd.text.replaceLocalString(EMetaText::OBJ_NAMES, ID);
  237. for(const auto & elem : creatures)
  238. bd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, elem.second[0]);
  239. }
  240. else if(ID == Obj::WAR_MACHINE_FACTORY)
  241. bd.text.appendLocalString(EMetaText::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  242. else
  243. throw std::runtime_error("Illegal dwelling!");
  244. cb->showBlockingDialog(&bd);
  245. }
  246. void CGDwelling::newTurn(CRandomGenerator & rand) const
  247. {
  248. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  249. return;
  250. //town growths and War Machines Factories are handled separately
  251. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  252. return;
  253. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  254. {
  255. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
  256. }
  257. bool change = false;
  258. SetAvailableCreatures sac;
  259. sac.creatures = creatures;
  260. sac.tid = id;
  261. for (size_t i = 0; i < creatures.size(); i++)
  262. {
  263. if(!creatures[i].second.empty())
  264. {
  265. bool creaturesAccumulate = false;
  266. if (tempOwner.isValidPlayer())
  267. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED);
  268. else
  269. creaturesAccumulate = VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_NEUTRAL);
  270. CCreature *cre = VLC->creh->objects[creatures[i].second[0]];
  271. TQuantity amount = cre->getGrowth() * (1 + cre->valOfBonuses(BonusType::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(BonusType::CREATURE_GROWTH);
  272. if (creaturesAccumulate && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  273. sac.creatures[i].first += amount;
  274. else
  275. sac.creatures[i].first = amount;
  276. change = true;
  277. }
  278. }
  279. if(change)
  280. cb->sendAndApply(&sac);
  281. updateGuards();
  282. }
  283. void CGDwelling::updateGuards() const
  284. {
  285. //TODO: store custom guard config and use it
  286. //TODO: store boolean flag for guards
  287. bool guarded = false;
  288. //default condition - creatures are of level 5 or higher
  289. for (auto creatureEntry : creatures)
  290. {
  291. if (VLC->creatures()->getByIndex(creatureEntry.second.at(0))->getLevel() >= 5 && ID != Obj::REFUGEE_CAMP)
  292. {
  293. guarded = true;
  294. break;
  295. }
  296. }
  297. if (guarded)
  298. {
  299. for (auto creatureEntry : creatures)
  300. {
  301. const CCreature * crea = VLC->creh->objects[creatureEntry.second.at(0)];
  302. SlotID slot = getSlotFor(crea->getId());
  303. if (hasStackAtSlot(slot)) //stack already exists, overwrite it
  304. {
  305. ChangeStackCount csc;
  306. csc.army = this->id;
  307. csc.slot = slot;
  308. csc.count = crea->getGrowth() * 3;
  309. csc.absoluteValue = true;
  310. cb->sendAndApply(&csc);
  311. }
  312. else //slot is empty, create whole new stack
  313. {
  314. InsertNewStack ns;
  315. ns.army = this->id;
  316. ns.slot = slot;
  317. ns.type = crea->getId();
  318. ns.count = crea->getGrowth() * 3;
  319. cb->sendAndApply(&ns);
  320. }
  321. }
  322. }
  323. }
  324. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  325. {
  326. CreatureID crid = creatures[0].second[0];
  327. auto *crs = crid.toCreature();
  328. TQuantity count = creatures[0].first;
  329. if(crs->getLevel() == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  330. {
  331. if(count) //there are available creatures
  332. {
  333. if (VLC->settings()->getBoolean(EGameSettings::DWELLINGS_ACCUMULATE_WHEN_OWNED))
  334. {
  335. SlotID testSlot = h->getSlotFor(crid);
  336. if(!testSlot.validSlot()) //no available slot - try merging army of visiting hero
  337. {
  338. std::pair<SlotID, SlotID> toMerge;
  339. if (h->mergableStacks(toMerge))
  340. {
  341. cb->moveStack(StackLocation(h, toMerge.first), StackLocation(h, toMerge.second), -1); //merge toMerge.first into toMerge.second
  342. assert(!h->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  343. }
  344. }
  345. }
  346. SlotID slot = h->getSlotFor(crid);
  347. if(!slot.validSlot()) //no available slot
  348. {
  349. InfoWindow iw;
  350. iw.type = EInfoWindowMode::AUTO;
  351. iw.player = h->tempOwner;
  352. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  353. iw.text.replaceLocalString(EMetaText::CRE_PL_NAMES, crid);
  354. cb->showInfoDialog(&iw);
  355. }
  356. else //give creatures
  357. {
  358. SetAvailableCreatures sac;
  359. sac.tid = id;
  360. sac.creatures = creatures;
  361. sac.creatures[0].first = 0;
  362. InfoWindow iw;
  363. iw.type = EInfoWindowMode::AUTO;
  364. iw.player = h->tempOwner;
  365. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 423); //%d %s join your army.
  366. iw.text.replaceNumber(count);
  367. iw.text.replaceLocalString(EMetaText::CRE_PL_NAMES, crid);
  368. cb->showInfoDialog(&iw);
  369. cb->sendAndApply(&sac);
  370. cb->addToSlot(StackLocation(h, slot), crs, count);
  371. }
  372. }
  373. else //there no creatures
  374. {
  375. InfoWindow iw;
  376. iw.type = EInfoWindowMode::AUTO;
  377. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 422); //There are no %s here to recruit.
  378. iw.text.replaceLocalString(EMetaText::CRE_PL_NAMES, crid);
  379. iw.player = h->tempOwner;
  380. cb->sendAndApply(&iw);
  381. }
  382. }
  383. else
  384. {
  385. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  386. {
  387. //there is 1 war machine available to recruit if hero doesn't have one
  388. SetAvailableCreatures sac;
  389. sac.tid = id;
  390. sac.creatures = creatures;
  391. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  392. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  393. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  394. cb->sendAndApply(&sac);
  395. }
  396. auto windowMode = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP) ? EOpenWindowMode::RECRUITMENT_FIRST : EOpenWindowMode::RECRUITMENT_ALL;
  397. cb->showObjectWindow(this, windowMode, h, true);
  398. }
  399. }
  400. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  401. {
  402. if (result.winner == 0)
  403. {
  404. onHeroVisit(hero);
  405. }
  406. }
  407. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  408. {
  409. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  410. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  411. {
  412. if(answer)
  413. cb->startBattleI(hero, this);
  414. }
  415. else if(answer)
  416. {
  417. heroAcceptsCreatures(hero);
  418. }
  419. }
  420. void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
  421. {
  422. switch (ID)
  423. {
  424. case Obj::WAR_MACHINE_FACTORY:
  425. case Obj::REFUGEE_CAMP:
  426. //do nothing
  427. break;
  428. case Obj::RANDOM_DWELLING:
  429. case Obj::RANDOM_DWELLING_LVL:
  430. case Obj::RANDOM_DWELLING_FACTION:
  431. if (!handler.saving)
  432. randomizationInfo = CGDwellingRandomizationInfo();
  433. randomizationInfo->serializeJson(handler);
  434. [[fallthrough]];
  435. default:
  436. serializeJsonOwner(handler);
  437. break;
  438. }
  439. }
  440. VCMI_LIB_NAMESPACE_END