CArtHandler.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. assert(constituents);
  178. for(const auto art : constituents)
  179. {
  180. auto possibleSlot = ArtifactUtils::getArtAnyPosition(&fittingSet, art->getId());
  181. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  182. {
  183. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  184. }
  185. else
  186. {
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. else
  193. {
  194. return simpleArtCanBePutAt(artSet, slot, assumeDestRemoved);
  195. }
  196. };
  197. if(slot == ArtifactPosition::TRANSITION_POS)
  198. return true;
  199. if(slot == ArtifactPosition::FIRST_AVAILABLE)
  200. {
  201. for(const auto & slot : possibleSlots.at(artSet->bearerType()))
  202. {
  203. if(artCanBePutAt(artSet, slot, assumeDestRemoved))
  204. return true;
  205. }
  206. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  207. }
  208. else if(ArtifactUtils::isSlotBackpack(slot))
  209. {
  210. return artCanBePutAt(artSet, GameConstants::BACKPACK_START, assumeDestRemoved);
  211. }
  212. else
  213. {
  214. return artCanBePutAt(artSet, slot, assumeDestRemoved);
  215. }
  216. }
  217. CArtifact::CArtifact()
  218. : iconIndex(ArtifactID::NONE),
  219. price(0)
  220. {
  221. setNodeType(ARTIFACT);
  222. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  223. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  224. possibleSlots[ArtBearer::COMMANDER];
  225. }
  226. //This destructor should be placed here to avoid side effects
  227. CArtifact::~CArtifact() = default;
  228. int CArtifact::getArtClassSerial() const
  229. {
  230. if(id == ArtifactID::SPELL_SCROLL)
  231. return 4;
  232. switch(aClass)
  233. {
  234. case ART_TREASURE:
  235. return 0;
  236. case ART_MINOR:
  237. return 1;
  238. case ART_MAJOR:
  239. return 2;
  240. case ART_RELIC:
  241. return 3;
  242. case ART_SPECIAL:
  243. return 5;
  244. }
  245. return -1;
  246. }
  247. std::string CArtifact::nodeName() const
  248. {
  249. return "Artifact: " + getNameTranslated();
  250. }
  251. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  252. {
  253. b->source = BonusSource::ARTIFACT;
  254. b->duration = BonusDuration::PERMANENT;
  255. b->description = getNameTranslated();
  256. CBonusSystemNode::addNewBonus(b);
  257. }
  258. const std::map<ArtBearer::ArtBearer, std::vector<ArtifactPosition>> & CArtifact::getPossibleSlots() const
  259. {
  260. return possibleSlots;
  261. }
  262. void CArtifact::updateFrom(const JsonNode& data)
  263. {
  264. //TODO:CArtifact::updateFrom
  265. }
  266. void CArtifact::setImage(int32_t iconIndex, std::string image, std::string large)
  267. {
  268. this->iconIndex = iconIndex;
  269. this->image = image;
  270. this->large = large;
  271. }
  272. CArtHandler::~CArtHandler() = default;
  273. std::vector<JsonNode> CArtHandler::loadLegacyData()
  274. {
  275. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_ARTIFACT);
  276. objects.resize(dataSize);
  277. std::vector<JsonNode> h3Data;
  278. h3Data.reserve(dataSize);
  279. #define ART_POS(x) #x ,
  280. const std::vector<std::string> artSlots = { ART_POS_LIST };
  281. #undef ART_POS
  282. static std::map<char, std::string> classes =
  283. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  284. CLegacyConfigParser parser("DATA/ARTRAITS.TXT");
  285. CLegacyConfigParser events("DATA/ARTEVENT.TXT");
  286. parser.endLine(); // header
  287. parser.endLine();
  288. for (size_t i = 0; i < dataSize; i++)
  289. {
  290. JsonNode artData;
  291. artData["text"]["name"].String() = parser.readString();
  292. artData["text"]["event"].String() = events.readString();
  293. artData["value"].Float() = parser.readNumber();
  294. for(const auto & artSlot : artSlots)
  295. {
  296. if(parser.readString() == "x")
  297. {
  298. artData["slot"].Vector().push_back(JsonNode());
  299. artData["slot"].Vector().back().String() = artSlot;
  300. }
  301. }
  302. artData["class"].String() = classes[parser.readString()[0]];
  303. artData["text"]["description"].String() = parser.readString();
  304. parser.endLine();
  305. events.endLine();
  306. h3Data.push_back(artData);
  307. }
  308. return h3Data;
  309. }
  310. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  311. {
  312. auto * object = loadFromJson(scope, data, name, objects.size());
  313. object->iconIndex = object->getIndex() + 5;
  314. objects.emplace_back(object);
  315. registerObject(scope, "artifact", name, object->id);
  316. }
  317. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  318. {
  319. auto * object = loadFromJson(scope, data, name, index);
  320. object->iconIndex = object->getIndex();
  321. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  322. objects[index] = object;
  323. registerObject(scope, "artifact", name, object->id);
  324. }
  325. const std::vector<std::string> & CArtHandler::getTypeNames() const
  326. {
  327. static const std::vector<std::string> typeNames = { "artifact" };
  328. return typeNames;
  329. }
  330. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  331. {
  332. assert(identifier.find(':') == std::string::npos);
  333. assert(!scope.empty());
  334. CArtifact * art = new CArtifact();
  335. if(!node["growing"].isNull())
  336. {
  337. for(auto bonus : node["growing"]["bonusesPerLevel"].Vector())
  338. {
  339. art->bonusesPerLevel.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  340. JsonUtils::parseBonus(bonus["bonus"], &art->bonusesPerLevel.back().second);
  341. }
  342. for(auto bonus : node["growing"]["thresholdBonuses"].Vector())
  343. {
  344. art->thresholdBonuses.emplace_back(static_cast<ui16>(bonus["level"].Float()), Bonus());
  345. JsonUtils::parseBonus(bonus["bonus"], &art->thresholdBonuses.back().second);
  346. }
  347. }
  348. art->id = ArtifactID(index);
  349. art->identifier = identifier;
  350. art->modScope = scope;
  351. const JsonNode & text = node["text"];
  352. VLC->generaltexth->registerString(scope, art->getNameTextID(), text["name"].String());
  353. VLC->generaltexth->registerString(scope, art->getDescriptionTextID(), text["description"].String());
  354. VLC->generaltexth->registerString(scope, art->getEventTextID(), text["event"].String());
  355. const JsonNode & graphics = node["graphics"];
  356. art->image = graphics["image"].String();
  357. if(!graphics["large"].isNull())
  358. art->large = graphics["large"].String();
  359. else
  360. art->large = art->image;
  361. art->advMapDef = graphics["map"].String();
  362. art->price = static_cast<ui32>(node["value"].Float());
  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