CArtHandler.cpp 33 KB

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