CArtHandler.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /*
  2. * CArtHandler.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 "ArtifactUtils.h"
  12. #include "CGeneralTextHandler.h"
  13. #include "GameSettings.h"
  14. #include "mapObjects/MapObjects.h"
  15. #include "constants/StringConstants.h"
  16. #include "mapObjectConstructors/AObjectTypeHandler.h"
  17. #include "mapObjectConstructors/CObjectClassesHandler.h"
  18. #include "serializer/JsonSerializeFormat.h"
  19. // Note: list must match entries in ArtTraits.txt
  20. #define ART_POS_LIST \
  21. ART_POS(SPELLBOOK) \
  22. ART_POS(MACH4) \
  23. ART_POS(MACH3) \
  24. ART_POS(MACH2) \
  25. ART_POS(MACH1) \
  26. ART_POS(MISC5) \
  27. ART_POS(MISC4) \
  28. ART_POS(MISC3) \
  29. ART_POS(MISC2) \
  30. ART_POS(MISC1) \
  31. ART_POS(FEET) \
  32. ART_POS(LEFT_RING) \
  33. ART_POS(RIGHT_RING) \
  34. ART_POS(TORSO) \
  35. ART_POS(LEFT_HAND) \
  36. ART_POS(RIGHT_HAND) \
  37. ART_POS(NECK) \
  38. ART_POS(SHOULDERS) \
  39. ART_POS(HEAD)
  40. VCMI_LIB_NAMESPACE_BEGIN
  41. bool CCombinedArtifact::isCombined() const
  42. {
  43. return !(constituents.empty());
  44. }
  45. const std::vector<CArtifact*> & CCombinedArtifact::getConstituents() const
  46. {
  47. return constituents;
  48. }
  49. const std::vector<CArtifact*> & CCombinedArtifact::getPartOf() const
  50. {
  51. return partOf;
  52. }
  53. bool CScrollArtifact::isScroll() const
  54. {
  55. return static_cast<const CArtifact*>(this)->getId() == ArtifactID::SPELL_SCROLL;
  56. }
  57. bool CGrowingArtifact::isGrowing() const
  58. {
  59. return !bonusesPerLevel.empty() || !thresholdBonuses.empty();
  60. }
  61. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel()
  62. {
  63. return bonusesPerLevel;
  64. }
  65. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getBonusesPerLevel() const
  66. {
  67. return bonusesPerLevel;
  68. }
  69. std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses()
  70. {
  71. return thresholdBonuses;
  72. }
  73. const std::vector <std::pair<ui16, Bonus>> & CGrowingArtifact::getThresholdBonuses() const
  74. {
  75. return thresholdBonuses;
  76. }
  77. int32_t CArtifact::getIndex() const
  78. {
  79. return id.toEnum();
  80. }
  81. int32_t CArtifact::getIconIndex() const
  82. {
  83. return iconIndex;
  84. }
  85. std::string CArtifact::getJsonKey() const
  86. {
  87. return modScope + ':' + identifier;
  88. }
  89. void CArtifact::registerIcons(const IconRegistar & cb) const
  90. {
  91. cb(getIconIndex(), 0, "ARTIFACT", image);
  92. cb(getIconIndex(), 0, "ARTIFACTLARGE", large);
  93. }
  94. ArtifactID CArtifact::getId() const
  95. {
  96. return id;
  97. }
  98. const IBonusBearer * CArtifact::getBonusBearer() const
  99. {
  100. return this;
  101. }
  102. std::string CArtifact::getDescriptionTranslated() const
  103. {
  104. return VLC->generaltexth->translate(getDescriptionTextID());
  105. }
  106. std::string CArtifact::getEventTranslated() const
  107. {
  108. return VLC->generaltexth->translate(getEventTextID());
  109. }
  110. std::string CArtifact::getNameTranslated() const
  111. {
  112. return VLC->generaltexth->translate(getNameTextID());
  113. }
  114. std::string CArtifact::getDescriptionTextID() const
  115. {
  116. return TextIdentifier("artifact", modScope, identifier, "description").get();
  117. }
  118. std::string CArtifact::getEventTextID() const
  119. {
  120. return TextIdentifier("artifact", modScope, identifier, "event").get();
  121. }
  122. std::string CArtifact::getNameTextID() const
  123. {
  124. return TextIdentifier("artifact", modScope, identifier, "name").get();
  125. }
  126. uint32_t CArtifact::getPrice() const
  127. {
  128. return price;
  129. }
  130. CreatureID CArtifact::getWarMachine() const
  131. {
  132. return warMachine;
  133. }
  134. bool CArtifact::isBig() const
  135. {
  136. return warMachine != CreatureID::NONE;
  137. }
  138. bool CArtifact::isTradable() const
  139. {
  140. switch(id)
  141. {
  142. case ArtifactID::SPELLBOOK:
  143. case ArtifactID::GRAIL:
  144. return false;
  145. default:
  146. return !isBig();
  147. }
  148. }
  149. bool CArtifact::canBePutAt(const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  150. {
  151. auto simpleArtCanBePutAt = [this](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  152. {
  153. if(ArtifactUtils::isSlotBackpack(slot))
  154. {
  155. if(isBig() || !ArtifactUtils::isBackpackFreeSlots(artSet))
  156. return false;
  157. return true;
  158. }
  159. if(!vstd::contains(possibleSlots.at(artSet->bearerType()), slot))
  160. return false;
  161. return artSet->isPositionFree(slot, assumeDestRemoved);
  162. };
  163. auto artCanBePutAt = [this, simpleArtCanBePutAt](const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) -> bool
  164. {
  165. if(isCombined())
  166. {
  167. if(!simpleArtCanBePutAt(artSet, slot, assumeDestRemoved))
  168. return false;
  169. if(ArtifactUtils::isSlotBackpack(slot))
  170. return true;
  171. CArtifactFittingSet fittingSet(artSet->bearerType());
  172. fittingSet.artifactsWorn = artSet->artifactsWorn;
  173. if(assumeDestRemoved)
  174. fittingSet.removeArtifact(slot);
  175. for(const auto art : constituents)
  176. {
  177. auto possibleSlot = ArtifactUtils::getArtAnyPosition(&fittingSet, art->getId());
  178. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  179. {
  180. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  181. }
  182. else
  183. {
  184. return false;
  185. }
  186. }
  187. return true;
  188. }
  189. else
  190. {
  191. return simpleArtCanBePutAt(artSet, slot, assumeDestRemoved);
  192. }
  193. };
  194. if(slot == ArtifactPosition::TRANSITION_POS)
  195. return true;
  196. if(slot == ArtifactPosition::FIRST_AVAILABLE)
  197. {
  198. for(const auto & slot : possibleSlots.at(artSet->bearerType()))
  199. {
  200. if(artCanBePutAt(artSet, slot, assumeDestRemoved))
  201. return true;
  202. }
  203. return artCanBePutAt(artSet, ArtifactPosition::BACKPACK_START, assumeDestRemoved);
  204. }
  205. else if(ArtifactUtils::isSlotBackpack(slot))
  206. {
  207. return artCanBePutAt(artSet, ArtifactPosition::BACKPACK_START, assumeDestRemoved);
  208. }
  209. else
  210. {
  211. return artCanBePutAt(artSet, slot, assumeDestRemoved);
  212. }
  213. }
  214. CArtifact::CArtifact()
  215. : iconIndex(ArtifactID::NONE),
  216. price(0)
  217. {
  218. setNodeType(ARTIFACT);
  219. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  220. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  221. possibleSlots[ArtBearer::COMMANDER];
  222. }
  223. //This destructor should be placed here to avoid side effects
  224. CArtifact::~CArtifact() = default;
  225. int CArtifact::getArtClassSerial() const
  226. {
  227. if(id == ArtifactID::SPELL_SCROLL)
  228. return 4;
  229. switch(aClass)
  230. {
  231. case ART_TREASURE:
  232. return 0;
  233. case ART_MINOR:
  234. return 1;
  235. case ART_MAJOR:
  236. return 2;
  237. case ART_RELIC:
  238. return 3;
  239. case ART_SPECIAL:
  240. return 5;
  241. }
  242. return -1;
  243. }
  244. std::string CArtifact::nodeName() const
  245. {
  246. return "Artifact: " + getNameTranslated();
  247. }
  248. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  249. {
  250. b->source = BonusSource::ARTIFACT;
  251. b->duration = BonusDuration::PERMANENT;
  252. b->description = getNameTranslated();
  253. CBonusSystemNode::addNewBonus(b);
  254. }
  255. const std::map<ArtBearer::ArtBearer, std::vector<ArtifactPosition>> & CArtifact::getPossibleSlots() const
  256. {
  257. return possibleSlots;
  258. }
  259. void CArtifact::updateFrom(const JsonNode& data)
  260. {
  261. //TODO:CArtifact::updateFrom
  262. }
  263. void CArtifact::setImage(int32_t iconIndex, std::string image, std::string large)
  264. {
  265. this->iconIndex = iconIndex;
  266. this->image = image;
  267. this->large = large;
  268. }
  269. CArtHandler::~CArtHandler() = default;
  270. std::vector<JsonNode> CArtHandler::loadLegacyData()
  271. {
  272. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_ARTIFACT);
  273. objects.resize(dataSize);
  274. std::vector<JsonNode> h3Data;
  275. h3Data.reserve(dataSize);
  276. #define ART_POS(x) #x ,
  277. const std::vector<std::string> artSlots = { ART_POS_LIST };
  278. #undef ART_POS
  279. static std::map<char, std::string> classes =
  280. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  281. CLegacyConfigParser parser(TextPath::builtin("DATA/ARTRAITS.TXT"));
  282. CLegacyConfigParser events(TextPath::builtin("DATA/ARTEVENT.TXT"));
  283. parser.endLine(); // header
  284. parser.endLine();
  285. for (size_t i = 0; i < dataSize; i++)
  286. {
  287. JsonNode artData;
  288. artData["text"]["name"].String() = parser.readString();
  289. artData["text"]["event"].String() = events.readString();
  290. artData["value"].Float() = parser.readNumber();
  291. for(const auto & artSlot : artSlots)
  292. {
  293. if(parser.readString() == "x")
  294. {
  295. artData["slot"].Vector().push_back(JsonNode());
  296. artData["slot"].Vector().back().String() = artSlot;
  297. }
  298. }
  299. artData["class"].String() = classes[parser.readString()[0]];
  300. artData["text"]["description"].String() = parser.readString();
  301. parser.endLine();
  302. events.endLine();
  303. h3Data.push_back(artData);
  304. }
  305. return h3Data;
  306. }
  307. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  308. {
  309. auto * object = loadFromJson(scope, data, name, objects.size());
  310. object->iconIndex = object->getIndex() + 5;
  311. objects.emplace_back(object);
  312. registerObject(scope, "artifact", name, object->id);
  313. }
  314. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  315. {
  316. auto * object = loadFromJson(scope, data, name, index);
  317. object->iconIndex = object->getIndex();
  318. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  319. objects[index] = object;
  320. registerObject(scope, "artifact", name, object->id);
  321. }
  322. const std::vector<std::string> & CArtHandler::getTypeNames() const
  323. {
  324. static const std::vector<std::string> typeNames = { "artifact" };
  325. return typeNames;
  326. }
  327. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  328. {
  329. assert(identifier.find(':') == std::string::npos);
  330. assert(!scope.empty());
  331. CArtifact * art = new CArtifact();
  332. if(!node["growing"].isNull())
  333. {
  334. for(auto bonus : node["growing"]["bonusesPerLevel"].Vector())
  335. {
  336. art->bonusesPerLevel.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  337. JsonUtils::parseBonus(bonus["bonus"], &art->bonusesPerLevel.back().second);
  338. }
  339. for(auto bonus : node["growing"]["thresholdBonuses"].Vector())
  340. {
  341. art->thresholdBonuses.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  342. JsonUtils::parseBonus(bonus["bonus"], &art->thresholdBonuses.back().second);
  343. }
  344. }
  345. art->id = ArtifactID(index);
  346. art->identifier = identifier;
  347. art->modScope = scope;
  348. const JsonNode & text = node["text"];
  349. VLC->generaltexth->registerString(scope, art->getNameTextID(), text["name"].String());
  350. VLC->generaltexth->registerString(scope, art->getDescriptionTextID(), text["description"].String());
  351. VLC->generaltexth->registerString(scope, art->getEventTextID(), text["event"].String());
  352. const JsonNode & graphics = node["graphics"];
  353. art->image = graphics["image"].String();
  354. if(!graphics["large"].isNull())
  355. art->large = graphics["large"].String();
  356. else
  357. art->large = art->image;
  358. art->advMapDef = graphics["map"].String();
  359. art->price = static_cast<ui32>(node["value"].Float());
  360. art->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  361. loadSlots(art, node);
  362. loadClass(art, node);
  363. loadType(art, node);
  364. loadComponents(art, node);
  365. for(const auto & b : node["bonuses"].Vector())
  366. {
  367. auto bonus = JsonUtils::parseBonus(b);
  368. art->addNewBonus(bonus);
  369. }
  370. const JsonNode & warMachine = node["warMachine"];
  371. if(warMachine.getType() == JsonNode::JsonType::DATA_STRING && !warMachine.String().empty())
  372. {
  373. VLC->identifiers()->requestIdentifier("creature", warMachine, [=](si32 id)
  374. {
  375. art->warMachine = CreatureID(id);
  376. //this assumes that creature object is stored before registration
  377. VLC->creh->objects.at(id)->warMachine = art->id;
  378. });
  379. }
  380. VLC->identifiers()->requestIdentifier(scope, "object", "artifact", [=](si32 index)
  381. {
  382. JsonNode conf;
  383. conf.setMeta(scope);
  384. VLC->objtypeh->loadSubObject(art->identifier, conf, Obj::ARTIFACT, art->getIndex());
  385. if(!art->advMapDef.empty())
  386. {
  387. JsonNode templ;
  388. templ["animation"].String() = art->advMapDef;
  389. templ.setMeta(scope);
  390. // add new template.
  391. // Necessary for objects added via mods that don't have any templates in H3
  392. VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->addTemplate(templ);
  393. }
  394. // object does not have any templates - this is not usable object (e.g. pseudo-art like lock)
  395. if(VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->getTemplates().empty())
  396. VLC->objtypeh->removeSubObject(Obj::ARTIFACT, art->getIndex());
  397. });
  398. return art;
  399. }
  400. int32_t ArtifactPositionBase::decode(const std::string & slotName)
  401. {
  402. #define ART_POS(x) { #x, ArtifactPosition::x },
  403. static const std::map<std::string, ArtifactPosition> artifactPositionMap = { ART_POS_LIST };
  404. #undef ART_POS
  405. auto it = artifactPositionMap.find (slotName);
  406. if (it != artifactPositionMap.end())
  407. return it->second;
  408. else
  409. return PRE_FIRST;
  410. }
  411. void CArtHandler::addSlot(CArtifact * art, const std::string & slotID) const
  412. {
  413. static const std::vector<ArtifactPosition> miscSlots =
  414. {
  415. ArtifactPosition::MISC1, ArtifactPosition::MISC2, ArtifactPosition::MISC3, ArtifactPosition::MISC4, ArtifactPosition::MISC5
  416. };
  417. static const std::vector<ArtifactPosition> ringSlots =
  418. {
  419. ArtifactPosition::RIGHT_RING, ArtifactPosition::LEFT_RING
  420. };
  421. if (slotID == "MISC")
  422. {
  423. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], miscSlots);
  424. }
  425. else if (slotID == "RING")
  426. {
  427. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], ringSlots);
  428. }
  429. else
  430. {
  431. auto slot = ArtifactPosition::decode(slotID);
  432. if (slot != ArtifactPosition::PRE_FIRST)
  433. art->possibleSlots[ArtBearer::HERO].push_back(slot);
  434. }
  435. }
  436. void CArtHandler::loadSlots(CArtifact * art, const JsonNode & node) const
  437. {
  438. if (!node["slot"].isNull()) //we assume non-hero slots are irrelevant?
  439. {
  440. if (node["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  441. addSlot(art, node["slot"].String());
  442. else
  443. {
  444. for (const JsonNode & slot : node["slot"].Vector())
  445. addSlot(art, slot.String());
  446. }
  447. std::sort(art->possibleSlots.at(ArtBearer::HERO).begin(), art->possibleSlots.at(ArtBearer::HERO).end());
  448. }
  449. }
  450. CArtifact::EartClass CArtHandler::stringToClass(const std::string & className)
  451. {
  452. static const std::map<std::string, CArtifact::EartClass> artifactClassMap =
  453. {
  454. {"TREASURE", CArtifact::ART_TREASURE},
  455. {"MINOR", CArtifact::ART_MINOR},
  456. {"MAJOR", CArtifact::ART_MAJOR},
  457. {"RELIC", CArtifact::ART_RELIC},
  458. {"SPECIAL", CArtifact::ART_SPECIAL}
  459. };
  460. auto it = artifactClassMap.find (className);
  461. if (it != artifactClassMap.end())
  462. return it->second;
  463. logMod->warn("Warning! Artifact rarity %s not recognized!", className);
  464. return CArtifact::ART_SPECIAL;
  465. }
  466. void CArtHandler::loadClass(CArtifact * art, const JsonNode & node) const
  467. {
  468. art->aClass = stringToClass(node["class"].String());
  469. }
  470. void CArtHandler::loadType(CArtifact * art, const JsonNode & node) const
  471. {
  472. #define ART_BEARER(x) { #x, ArtBearer::x },
  473. static const std::map<std::string, int> artifactBearerMap = { ART_BEARER_LIST };
  474. #undef ART_BEARER
  475. for (const JsonNode & b : node["type"].Vector())
  476. {
  477. auto it = artifactBearerMap.find (b.String());
  478. if (it != artifactBearerMap.end())
  479. {
  480. int bearerType = it->second;
  481. switch (bearerType)
  482. {
  483. case ArtBearer::HERO://TODO: allow arts having several possible bearers
  484. break;
  485. case ArtBearer::COMMANDER:
  486. makeItCommanderArt (art); //original artifacts should have only one bearer type
  487. break;
  488. case ArtBearer::CREATURE:
  489. makeItCreatureArt (art);
  490. break;
  491. }
  492. }
  493. else
  494. logMod->warn("Warning! Artifact type %s not recognized!", b.String());
  495. }
  496. }
  497. void CArtHandler::loadComponents(CArtifact * art, const JsonNode & node)
  498. {
  499. if (!node["components"].isNull())
  500. {
  501. for(const auto & component : node["components"].Vector())
  502. {
  503. VLC->identifiers()->requestIdentifier("artifact", component, [=](si32 id)
  504. {
  505. // when this code is called both combinational art as well as component are loaded
  506. // so it is safe to access any of them
  507. art->constituents.push_back(objects[id]);
  508. objects[id]->partOf.push_back(art);
  509. });
  510. }
  511. }
  512. }
  513. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags, std::function<bool(ArtifactID)> accepts)
  514. {
  515. auto getAllowedArts = [&](std::vector<ConstTransitivePtr<CArtifact> > &out, std::vector<CArtifact*> *arts, CArtifact::EartClass flag)
  516. {
  517. if (arts->empty()) //restock available arts
  518. fillList(*arts, flag);
  519. for (auto & arts_i : *arts)
  520. {
  521. if (accepts(arts_i->id))
  522. {
  523. CArtifact *art = arts_i;
  524. out.emplace_back(art);
  525. }
  526. }
  527. };
  528. auto getAllowed = [&](std::vector<ConstTransitivePtr<CArtifact> > &out)
  529. {
  530. if (flags & CArtifact::ART_TREASURE)
  531. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  532. if (flags & CArtifact::ART_MINOR)
  533. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  534. if (flags & CArtifact::ART_MAJOR)
  535. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  536. if (flags & CArtifact::ART_RELIC)
  537. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  538. if(out.empty()) //no artifact of specified rarity, we need to take another one
  539. {
  540. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  541. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  542. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  543. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  544. }
  545. if(out.empty()) //no arts are available at all
  546. {
  547. out.resize (64);
  548. std::fill_n (out.begin(), 64, objects[2]); //Give Grail - this can't be banned (hopefully)
  549. }
  550. };
  551. std::vector<ConstTransitivePtr<CArtifact> > out;
  552. getAllowed(out);
  553. ArtifactID artID = (*RandomGeneratorUtil::nextItem(out, rand))->id;
  554. erasePickedArt(artID);
  555. return artID;
  556. }
  557. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::function<bool(ArtifactID)> accepts)
  558. {
  559. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  560. }
  561. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags)
  562. {
  563. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  564. }
  565. void CArtHandler::makeItCreatureArt(CArtifact * a, bool onlyCreature)
  566. {
  567. if (onlyCreature)
  568. {
  569. a->possibleSlots[ArtBearer::HERO].clear();
  570. a->possibleSlots[ArtBearer::COMMANDER].clear();
  571. }
  572. a->possibleSlots[ArtBearer::CREATURE].push_back(ArtifactPosition::CREATURE_SLOT);
  573. }
  574. void CArtHandler::makeItCommanderArt(CArtifact * a, bool onlyCommander)
  575. {
  576. if (onlyCommander)
  577. {
  578. a->possibleSlots[ArtBearer::HERO].clear();
  579. a->possibleSlots[ArtBearer::CREATURE].clear();
  580. }
  581. for (int i = ArtifactPosition::COMMANDER1; i <= ArtifactPosition::COMMANDER6; ++i)
  582. a->possibleSlots[ArtBearer::COMMANDER].push_back(ArtifactPosition(i));
  583. }
  584. bool CArtHandler::legalArtifact(const ArtifactID & id)
  585. {
  586. auto art = objects[id];
  587. //assert ( (!art->constituents) || art->constituents->size() ); //artifacts is not combined or has some components
  588. if(art->isCombined())
  589. return false; //no combo artifacts spawning
  590. if(art->aClass < CArtifact::ART_TREASURE || art->aClass > CArtifact::ART_RELIC)
  591. return false; // invalid class
  592. if(!art->possibleSlots[ArtBearer::HERO].empty())
  593. return true;
  594. if(!art->possibleSlots[ArtBearer::CREATURE].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_ARTIFACT))
  595. return true;
  596. if(!art->possibleSlots[ArtBearer::COMMANDER].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS))
  597. return true;
  598. return false;
  599. }
  600. void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
  601. {
  602. allowedArtifacts.clear();
  603. treasures.clear();
  604. minors.clear();
  605. majors.clear();
  606. relics.clear();
  607. for (ArtifactID i=ArtifactID::SPELLBOOK; i < ArtifactID(static_cast<si32>(objects.size())); i.advance(1))
  608. {
  609. if (allowed[i] && legalArtifact(ArtifactID(i)))
  610. allowedArtifacts.push_back(objects[i]);
  611. //keep im mind that artifact can be worn by more than one type of bearer
  612. }
  613. }
  614. std::vector<bool> CArtHandler::getDefaultAllowed() const
  615. {
  616. std::vector<bool> allowedArtifacts;
  617. allowedArtifacts.resize(127, true);
  618. allowedArtifacts.resize(141, false);
  619. allowedArtifacts.resize(size(), true);
  620. return allowedArtifacts;
  621. }
  622. void CArtHandler::erasePickedArt(const ArtifactID & id)
  623. {
  624. CArtifact *art = objects[id];
  625. std::vector<CArtifact*> * artifactList = nullptr;
  626. switch(art->aClass)
  627. {
  628. case CArtifact::ART_TREASURE:
  629. artifactList = &treasures;
  630. break;
  631. case CArtifact::ART_MINOR:
  632. artifactList = &minors;
  633. break;
  634. case CArtifact::ART_MAJOR:
  635. artifactList = &majors;
  636. break;
  637. case CArtifact::ART_RELIC:
  638. artifactList = &relics;
  639. break;
  640. default:
  641. logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
  642. return;
  643. }
  644. if(artifactList->empty())
  645. fillList(*artifactList, art->aClass);
  646. auto itr = vstd::find(*artifactList, art);
  647. if(itr != artifactList->end())
  648. {
  649. artifactList->erase(itr);
  650. }
  651. else
  652. logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
  653. }
  654. void CArtHandler::fillList( std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass )
  655. {
  656. assert(listToBeFilled.empty());
  657. for (auto & elem : allowedArtifacts)
  658. {
  659. if (elem->aClass == artifactClass)
  660. listToBeFilled.push_back(elem);
  661. }
  662. }
  663. void CArtHandler::afterLoadFinalization()
  664. {
  665. //All artifacts have their id, so we can properly update their bonuses' source ids.
  666. for(auto &art : objects)
  667. {
  668. for(auto &bonus : art->getExportedBonusList())
  669. {
  670. assert(art == objects[art->id]);
  671. assert(bonus->source == BonusSource::ARTIFACT);
  672. bonus->sid = art->id;
  673. }
  674. }
  675. CBonusSystemNode::treeHasChanged();
  676. }
  677. CArtifactSet::~CArtifactSet() = default;
  678. const CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked) const
  679. {
  680. if(const ArtSlotInfo * si = getSlot(pos))
  681. {
  682. if(si->artifact && (!excludeLocked || !si->locked))
  683. return si->artifact;
  684. }
  685. return nullptr;
  686. }
  687. CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked)
  688. {
  689. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  690. }
  691. ArtifactPosition CArtifactSet::getArtPos(const ArtifactID & aid, bool onlyWorn, bool allowLocked) const
  692. {
  693. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  694. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  695. }
  696. ArtifactPosition CArtifactSet::getArtBackpackPos(const ArtifactID & aid) const
  697. {
  698. const auto result = getBackpackArtPositions(aid);
  699. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  700. }
  701. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(const ArtifactID & aid, bool onlyWorn, bool allowLocked, bool getAll) const
  702. {
  703. std::vector<ArtifactPosition> result;
  704. for(const auto & slotInfo : artifactsWorn)
  705. if(slotInfo.second.artifact->getTypeId() == aid && (allowLocked || !slotInfo.second.locked))
  706. result.push_back(slotInfo.first);
  707. if(onlyWorn)
  708. return result;
  709. if(!getAll && !result.empty())
  710. return result;
  711. auto backpackPositions = getBackpackArtPositions(aid);
  712. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  713. return result;
  714. }
  715. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(const ArtifactID & aid) const
  716. {
  717. std::vector<ArtifactPosition> result;
  718. si32 backpackPosition = ArtifactPosition::BACKPACK_START;
  719. for(const auto & artInfo : artifactsInBackpack)
  720. {
  721. const auto * art = artInfo.getArt();
  722. if(art && art->artType->getId() == aid)
  723. result.emplace_back(backpackPosition);
  724. backpackPosition++;
  725. }
  726. return result;
  727. }
  728. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  729. {
  730. for(auto i : artifactsWorn)
  731. if(i.second.artifact == art)
  732. return i.first;
  733. for(int i = 0; i < artifactsInBackpack.size(); i++)
  734. if(artifactsInBackpack[i].artifact == art)
  735. return ArtifactPosition::BACKPACK_START + i;
  736. return ArtifactPosition::PRE_FIRST;
  737. }
  738. const CArtifactInstance * CArtifactSet::getArtByInstanceId(const ArtifactInstanceID & artInstId) const
  739. {
  740. for(auto i : artifactsWorn)
  741. if(i.second.artifact->getId() == artInstId)
  742. return i.second.artifact;
  743. for(auto i : artifactsInBackpack)
  744. if(i.artifact->getId() == artInstId)
  745. return i.artifact;
  746. return nullptr;
  747. }
  748. const ArtifactPosition CArtifactSet::getSlotByInstance(const CArtifactInstance * artInst) const
  749. {
  750. if(artInst)
  751. {
  752. for(const auto & slot : artInst->artType->getPossibleSlots().at(bearerType()))
  753. if(getArt(slot) == artInst)
  754. return slot;
  755. ArtifactPosition backpackSlot = ArtifactPosition::BACKPACK_START;
  756. for(auto & slotInfo : artifactsInBackpack)
  757. {
  758. if(slotInfo.getArt() == artInst)
  759. return backpackSlot;
  760. backpackSlot = ArtifactPosition(backpackSlot + 1);
  761. }
  762. }
  763. return ArtifactPosition::PRE_FIRST;
  764. }
  765. bool CArtifactSet::hasArt(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  766. {
  767. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  768. }
  769. bool CArtifactSet::hasArtBackpack(const ArtifactID & aid) const
  770. {
  771. return !getBackpackArtPositions(aid).empty();
  772. }
  773. unsigned CArtifactSet::getArtPosCount(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  774. {
  775. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  776. if(!allPositions.empty())
  777. return allPositions.size();
  778. if(searchBackpackAssemblies && getHiddenArt(aid))
  779. return 1;
  780. return 0;
  781. }
  782. CArtifactSet::ArtPlacementMap CArtifactSet::putArtifact(ArtifactPosition slot, CArtifactInstance * art)
  783. {
  784. ArtPlacementMap resArtPlacement;
  785. setNewArtSlot(slot, art, false);
  786. if(art->artType->isCombined() && ArtifactUtils::isSlotEquipment(slot))
  787. {
  788. const CArtifactInstance * mainPart = nullptr;
  789. for(const auto & part : art->getPartsInfo())
  790. if(vstd::contains(part.art->artType->getPossibleSlots().at(bearerType()), slot)
  791. && (part.slot == ArtifactPosition::PRE_FIRST))
  792. {
  793. mainPart = part.art;
  794. break;
  795. }
  796. for(const auto & part : art->getPartsInfo())
  797. {
  798. if(part.art != mainPart)
  799. {
  800. auto partSlot = part.slot;
  801. if(!part.art->artType->canBePutAt(this, partSlot))
  802. partSlot = ArtifactUtils::getArtAnyPosition(this, part.art->getTypeId());
  803. assert(ArtifactUtils::isSlotEquipment(partSlot));
  804. setNewArtSlot(partSlot, part.art, true);
  805. resArtPlacement.emplace(std::make_pair(part.art, partSlot));
  806. }
  807. else
  808. {
  809. resArtPlacement.emplace(std::make_pair(part.art, part.slot));
  810. }
  811. }
  812. }
  813. return resArtPlacement;
  814. }
  815. void CArtifactSet::removeArtifact(ArtifactPosition slot)
  816. {
  817. auto art = getArt(slot, false);
  818. if(art)
  819. {
  820. if(art->isCombined())
  821. {
  822. for(auto & part : art->getPartsInfo())
  823. {
  824. if(getArt(part.slot, false))
  825. eraseArtSlot(part.slot);
  826. }
  827. }
  828. eraseArtSlot(slot);
  829. }
  830. }
  831. std::pair<const CArtifactInstance *, const CArtifactInstance *> CArtifactSet::searchForConstituent(const ArtifactID & aid) const
  832. {
  833. for(const auto & slot : artifactsInBackpack)
  834. {
  835. auto art = slot.artifact;
  836. if(art->isCombined())
  837. {
  838. for(auto & ci : art->getPartsInfo())
  839. {
  840. if(ci.art->getTypeId() == aid)
  841. {
  842. return {art, ci.art};
  843. }
  844. }
  845. }
  846. }
  847. return {nullptr, nullptr};
  848. }
  849. const CArtifactInstance * CArtifactSet::getHiddenArt(const ArtifactID & aid) const
  850. {
  851. return searchForConstituent(aid).second;
  852. }
  853. const CArtifactInstance * CArtifactSet::getAssemblyByConstituent(const ArtifactID & aid) const
  854. {
  855. return searchForConstituent(aid).first;
  856. }
  857. const ArtSlotInfo * CArtifactSet::getSlot(const ArtifactPosition & pos) const
  858. {
  859. if(pos == ArtifactPosition::TRANSITION_POS)
  860. {
  861. // Always add to the end. Always take from the beginning.
  862. if(artifactsTransitionPos.empty())
  863. return nullptr;
  864. else
  865. return &(*artifactsTransitionPos.begin());
  866. }
  867. if(vstd::contains(artifactsWorn, pos))
  868. return &artifactsWorn.at(pos);
  869. if(pos >= ArtifactPosition::AFTER_LAST )
  870. {
  871. int backpackPos = (int)pos - ArtifactPosition::BACKPACK_START;
  872. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  873. return nullptr;
  874. else
  875. return &artifactsInBackpack[backpackPos];
  876. }
  877. return nullptr;
  878. }
  879. bool CArtifactSet::isPositionFree(const ArtifactPosition & pos, bool onlyLockCheck) const
  880. {
  881. if(const ArtSlotInfo *s = getSlot(pos))
  882. return (onlyLockCheck || !s->artifact) && !s->locked;
  883. return true; //no slot means not used
  884. }
  885. void CArtifactSet::setNewArtSlot(const ArtifactPosition & slot, ConstTransitivePtr<CArtifactInstance> art, bool locked)
  886. {
  887. assert(!vstd::contains(artifactsWorn, slot));
  888. ArtSlotInfo * slotInfo;
  889. if(slot == ArtifactPosition::TRANSITION_POS)
  890. {
  891. // Always add to the end. Always take from the beginning.
  892. artifactsTransitionPos.emplace_back();
  893. slotInfo = &artifactsTransitionPos.back();
  894. }
  895. else if(ArtifactUtils::isSlotEquipment(slot))
  896. {
  897. slotInfo = &artifactsWorn[slot];
  898. }
  899. else
  900. {
  901. auto position = artifactsInBackpack.begin() + slot - ArtifactPosition::BACKPACK_START;
  902. slotInfo = &(*artifactsInBackpack.emplace(position, ArtSlotInfo()));
  903. }
  904. slotInfo->artifact = art;
  905. slotInfo->locked = locked;
  906. }
  907. void CArtifactSet::eraseArtSlot(const ArtifactPosition & slot)
  908. {
  909. if(slot == ArtifactPosition::TRANSITION_POS)
  910. {
  911. assert(!artifactsTransitionPos.empty());
  912. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  913. }
  914. else if(ArtifactUtils::isSlotBackpack(slot))
  915. {
  916. auto backpackSlot = ArtifactPosition(slot - ArtifactPosition::BACKPACK_START);
  917. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  918. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  919. }
  920. else
  921. {
  922. artifactsWorn.erase(slot);
  923. }
  924. }
  925. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  926. {
  927. for(auto & elem : artifactsWorn)
  928. if(elem.second.artifact && !elem.second.locked)
  929. node->attachTo(*elem.second.artifact);
  930. }
  931. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  932. {
  933. //todo: creature and commander artifacts
  934. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  935. return;
  936. if(!handler.saving)
  937. {
  938. assert(map);
  939. artifactsInBackpack.clear();
  940. artifactsWorn.clear();
  941. }
  942. auto s = handler.enterStruct(fieldName);
  943. switch(bearerType())
  944. {
  945. case ArtBearer::HERO:
  946. serializeJsonHero(handler, map);
  947. break;
  948. case ArtBearer::CREATURE:
  949. serializeJsonCreature(handler, map);
  950. break;
  951. case ArtBearer::COMMANDER:
  952. serializeJsonCommander(handler, map);
  953. break;
  954. default:
  955. assert(false);
  956. break;
  957. }
  958. }
  959. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  960. {
  961. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  962. {
  963. serializeJsonSlot(handler, ap, map);
  964. }
  965. std::vector<ArtifactID> backpackTemp;
  966. if(handler.saving)
  967. {
  968. backpackTemp.reserve(artifactsInBackpack.size());
  969. for(const ArtSlotInfo & info : artifactsInBackpack)
  970. backpackTemp.push_back(info.artifact->getTypeId());
  971. }
  972. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  973. if(!handler.saving)
  974. {
  975. for(const ArtifactID & artifactID : backpackTemp)
  976. {
  977. auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
  978. auto slot = ArtifactPosition::BACKPACK_START + (si32)artifactsInBackpack.size();
  979. if(artifact->artType->canBePutAt(this, slot))
  980. putArtifact(slot, artifact);
  981. }
  982. }
  983. }
  984. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  985. {
  986. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  987. }
  988. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  989. {
  990. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  991. }
  992. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  993. {
  994. ArtifactID artifactID;
  995. if(handler.saving)
  996. {
  997. const ArtSlotInfo * info = getSlot(slot);
  998. if(info != nullptr && !info->locked)
  999. {
  1000. artifactID = info->artifact->getTypeId();
  1001. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1002. }
  1003. }
  1004. else
  1005. {
  1006. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1007. if(artifactID != ArtifactID::NONE)
  1008. {
  1009. auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
  1010. if(artifact->artType->canBePutAt(this, slot))
  1011. {
  1012. putArtifact(slot, artifact);
  1013. }
  1014. else
  1015. {
  1016. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  1017. }
  1018. }
  1019. }
  1020. }
  1021. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer):
  1022. Bearer(Bearer)
  1023. {
  1024. }
  1025. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  1026. {
  1027. return this->Bearer;
  1028. }
  1029. VCMI_LIB_NAMESPACE_END