CArtHandler.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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.toEnum())
  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. std::set<ArtifactID> potentialPicks;
  516. // Select artifacts that satisfy provided criterias
  517. for (auto const * artifact : allowedArtifacts)
  518. {
  519. assert(artifact->aClass != CArtifact::ART_SPECIAL); // should be filtered out when allowedArtifacts is initialized
  520. if ((flags & CArtifact::ART_TREASURE) == 0 && artifact->aClass == CArtifact::ART_TREASURE)
  521. continue;
  522. if ((flags & CArtifact::ART_MINOR) == 0 && artifact->aClass == CArtifact::ART_MINOR)
  523. continue;
  524. if ((flags & CArtifact::ART_MAJOR) == 0 && artifact->aClass == CArtifact::ART_MAJOR)
  525. continue;
  526. if ((flags & CArtifact::ART_RELIC) == 0 && artifact->aClass == CArtifact::ART_RELIC)
  527. continue;
  528. if (!accepts(artifact->id))
  529. continue;
  530. potentialPicks.insert(artifact->id);
  531. }
  532. return pickRandomArtifact(rand, potentialPicks);
  533. }
  534. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::set<ArtifactID> potentialPicks)
  535. {
  536. // No allowed artifacts at all - give Grail - this can't be banned (hopefully)
  537. // FIXME: investigate how such cases are handled by H3 - some heavily customized user-made maps likely rely on H3 behavior
  538. if (potentialPicks.empty())
  539. {
  540. logGlobal->warn("Failed to find artifact that matches requested parameters!");
  541. return ArtifactID::GRAIL;
  542. }
  543. // Find how many times least used artifacts were picked by randomizer
  544. int leastUsedTimes = std::numeric_limits<int>::max();
  545. for (auto const & artifact : potentialPicks)
  546. if (allocatedArtifacts[artifact] < leastUsedTimes)
  547. leastUsedTimes = allocatedArtifacts[artifact];
  548. // Pick all artifacts that were used least number of times
  549. std::set<ArtifactID> preferredPicks;
  550. for (auto const & artifact : potentialPicks)
  551. if (allocatedArtifacts[artifact] == leastUsedTimes)
  552. preferredPicks.insert(artifact);
  553. assert(!preferredPicks.empty());
  554. ArtifactID artID = *RandomGeneratorUtil::nextItem(preferredPicks, rand);
  555. allocatedArtifacts[artID] += 1; // record +1 more usage
  556. return artID;
  557. }
  558. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::function<bool(ArtifactID)> accepts)
  559. {
  560. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  561. }
  562. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags)
  563. {
  564. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  565. }
  566. void CArtHandler::makeItCreatureArt(CArtifact * a, bool onlyCreature)
  567. {
  568. if (onlyCreature)
  569. {
  570. a->possibleSlots[ArtBearer::HERO].clear();
  571. a->possibleSlots[ArtBearer::COMMANDER].clear();
  572. }
  573. a->possibleSlots[ArtBearer::CREATURE].push_back(ArtifactPosition::CREATURE_SLOT);
  574. }
  575. void CArtHandler::makeItCommanderArt(CArtifact * a, bool onlyCommander)
  576. {
  577. if (onlyCommander)
  578. {
  579. a->possibleSlots[ArtBearer::HERO].clear();
  580. a->possibleSlots[ArtBearer::CREATURE].clear();
  581. }
  582. for(const auto & slot : ArtifactUtils::commanderSlots())
  583. a->possibleSlots[ArtBearer::COMMANDER].push_back(ArtifactPosition(slot));
  584. }
  585. bool CArtHandler::legalArtifact(const ArtifactID & id)
  586. {
  587. auto art = objects[id];
  588. //assert ( (!art->constituents) || art->constituents->size() ); //artifacts is not combined or has some components
  589. if(art->isCombined())
  590. return false; //no combo artifacts spawning
  591. if(art->aClass < CArtifact::ART_TREASURE || art->aClass > CArtifact::ART_RELIC)
  592. return false; // invalid class
  593. if(!art->possibleSlots[ArtBearer::HERO].empty())
  594. return true;
  595. if(!art->possibleSlots[ArtBearer::CREATURE].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_ARTIFACT))
  596. return true;
  597. if(!art->possibleSlots[ArtBearer::COMMANDER].empty() && VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS))
  598. return true;
  599. return false;
  600. }
  601. void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
  602. {
  603. allowedArtifacts.clear();
  604. allocatedArtifacts.clear();
  605. for (ArtifactID i=ArtifactID::SPELLBOOK; i < ArtifactID(static_cast<si32>(objects.size())); i.advance(1))
  606. {
  607. if (allowed[i] && legalArtifact(ArtifactID(i)))
  608. allowedArtifacts.push_back(objects[i]);
  609. //keep im mind that artifact can be worn by more than one type of bearer
  610. }
  611. }
  612. std::vector<bool> CArtHandler::getDefaultAllowed() const
  613. {
  614. std::vector<bool> allowedArtifacts;
  615. allowedArtifacts.resize(127, true);
  616. allowedArtifacts.resize(141, false);
  617. allowedArtifacts.resize(size(), true);
  618. return allowedArtifacts;
  619. }
  620. void CArtHandler::afterLoadFinalization()
  621. {
  622. //All artifacts have their id, so we can properly update their bonuses' source ids.
  623. for(auto &art : objects)
  624. {
  625. for(auto &bonus : art->getExportedBonusList())
  626. {
  627. assert(art == objects[art->id]);
  628. assert(bonus->source == BonusSource::ARTIFACT);
  629. bonus->sid = BonusSourceID(art->id);
  630. }
  631. }
  632. CBonusSystemNode::treeHasChanged();
  633. }
  634. CArtifactSet::~CArtifactSet() = default;
  635. const CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked) const
  636. {
  637. if(const ArtSlotInfo * si = getSlot(pos))
  638. {
  639. if(si->artifact && (!excludeLocked || !si->locked))
  640. return si->artifact;
  641. }
  642. return nullptr;
  643. }
  644. CArtifactInstance * CArtifactSet::getArt(const ArtifactPosition & pos, bool excludeLocked)
  645. {
  646. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  647. }
  648. ArtifactPosition CArtifactSet::getArtPos(const ArtifactID & aid, bool onlyWorn, bool allowLocked) const
  649. {
  650. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  651. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  652. }
  653. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(const ArtifactID & aid, bool onlyWorn, bool allowLocked, bool getAll) const
  654. {
  655. std::vector<ArtifactPosition> result;
  656. for(const auto & slotInfo : artifactsWorn)
  657. if(slotInfo.second.artifact->getTypeId() == aid && (allowLocked || !slotInfo.second.locked))
  658. result.push_back(slotInfo.first);
  659. if(onlyWorn)
  660. return result;
  661. if(!getAll && !result.empty())
  662. return result;
  663. auto backpackPositions = getBackpackArtPositions(aid);
  664. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  665. return result;
  666. }
  667. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(const ArtifactID & aid) const
  668. {
  669. std::vector<ArtifactPosition> result;
  670. si32 backpackPosition = ArtifactPosition::BACKPACK_START;
  671. for(const auto & artInfo : artifactsInBackpack)
  672. {
  673. const auto * art = artInfo.getArt();
  674. if(art && art->artType->getId() == aid)
  675. result.emplace_back(backpackPosition);
  676. backpackPosition++;
  677. }
  678. return result;
  679. }
  680. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  681. {
  682. for(auto i : artifactsWorn)
  683. if(i.second.artifact == art)
  684. return i.first;
  685. for(int i = 0; i < artifactsInBackpack.size(); i++)
  686. if(artifactsInBackpack[i].artifact == art)
  687. return ArtifactPosition::BACKPACK_START + i;
  688. return ArtifactPosition::PRE_FIRST;
  689. }
  690. const CArtifactInstance * CArtifactSet::getArtByInstanceId(const ArtifactInstanceID & artInstId) const
  691. {
  692. for(auto i : artifactsWorn)
  693. if(i.second.artifact->getId() == artInstId)
  694. return i.second.artifact;
  695. for(auto i : artifactsInBackpack)
  696. if(i.artifact->getId() == artInstId)
  697. return i.artifact;
  698. return nullptr;
  699. }
  700. const ArtifactPosition CArtifactSet::getSlotByInstance(const CArtifactInstance * artInst) const
  701. {
  702. if(artInst)
  703. {
  704. for(const auto & slot : artInst->artType->getPossibleSlots().at(bearerType()))
  705. if(getArt(slot) == artInst)
  706. return slot;
  707. ArtifactPosition backpackSlot = ArtifactPosition::BACKPACK_START;
  708. for(auto & slotInfo : artifactsInBackpack)
  709. {
  710. if(slotInfo.getArt() == artInst)
  711. return backpackSlot;
  712. backpackSlot = ArtifactPosition(backpackSlot + 1);
  713. }
  714. }
  715. return ArtifactPosition::PRE_FIRST;
  716. }
  717. bool CArtifactSet::hasArt(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  718. {
  719. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  720. }
  721. bool CArtifactSet::hasArtBackpack(const ArtifactID & aid) const
  722. {
  723. return !getBackpackArtPositions(aid).empty();
  724. }
  725. unsigned CArtifactSet::getArtPosCount(const ArtifactID & aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  726. {
  727. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  728. if(!allPositions.empty())
  729. return allPositions.size();
  730. if(searchBackpackAssemblies && getHiddenArt(aid))
  731. return 1;
  732. return 0;
  733. }
  734. CArtifactSet::ArtPlacementMap CArtifactSet::putArtifact(ArtifactPosition slot, CArtifactInstance * art)
  735. {
  736. ArtPlacementMap resArtPlacement;
  737. setNewArtSlot(slot, art, false);
  738. if(art->artType->isCombined() && ArtifactUtils::isSlotEquipment(slot))
  739. {
  740. const CArtifactInstance * mainPart = nullptr;
  741. for(const auto & part : art->getPartsInfo())
  742. if(vstd::contains(part.art->artType->getPossibleSlots().at(bearerType()), slot)
  743. && (part.slot == ArtifactPosition::PRE_FIRST))
  744. {
  745. mainPart = part.art;
  746. break;
  747. }
  748. for(const auto & part : art->getPartsInfo())
  749. {
  750. if(part.art != mainPart)
  751. {
  752. auto partSlot = part.slot;
  753. if(!part.art->artType->canBePutAt(this, partSlot))
  754. partSlot = ArtifactUtils::getArtAnyPosition(this, part.art->getTypeId());
  755. assert(ArtifactUtils::isSlotEquipment(partSlot));
  756. setNewArtSlot(partSlot, part.art, true);
  757. resArtPlacement.emplace(std::make_pair(part.art, partSlot));
  758. }
  759. else
  760. {
  761. resArtPlacement.emplace(std::make_pair(part.art, part.slot));
  762. }
  763. }
  764. }
  765. return resArtPlacement;
  766. }
  767. void CArtifactSet::removeArtifact(ArtifactPosition slot)
  768. {
  769. auto art = getArt(slot, false);
  770. if(art)
  771. {
  772. if(art->isCombined())
  773. {
  774. for(auto & part : art->getPartsInfo())
  775. {
  776. if(getArt(part.slot, false))
  777. eraseArtSlot(part.slot);
  778. }
  779. }
  780. eraseArtSlot(slot);
  781. }
  782. }
  783. std::pair<const CArtifactInstance *, const CArtifactInstance *> CArtifactSet::searchForConstituent(const ArtifactID & aid) const
  784. {
  785. for(const auto & slot : artifactsInBackpack)
  786. {
  787. auto art = slot.artifact;
  788. if(art->isCombined())
  789. {
  790. for(auto & ci : art->getPartsInfo())
  791. {
  792. if(ci.art->getTypeId() == aid)
  793. {
  794. return {art, ci.art};
  795. }
  796. }
  797. }
  798. }
  799. return {nullptr, nullptr};
  800. }
  801. const CArtifactInstance * CArtifactSet::getHiddenArt(const ArtifactID & aid) const
  802. {
  803. return searchForConstituent(aid).second;
  804. }
  805. const CArtifactInstance * CArtifactSet::getAssemblyByConstituent(const ArtifactID & aid) const
  806. {
  807. return searchForConstituent(aid).first;
  808. }
  809. const ArtSlotInfo * CArtifactSet::getSlot(const ArtifactPosition & pos) const
  810. {
  811. if(pos == ArtifactPosition::TRANSITION_POS)
  812. {
  813. // Always add to the end. Always take from the beginning.
  814. if(artifactsTransitionPos.empty())
  815. return nullptr;
  816. else
  817. return &(*artifactsTransitionPos.begin());
  818. }
  819. if(vstd::contains(artifactsWorn, pos))
  820. return &artifactsWorn.at(pos);
  821. if(ArtifactUtils::isSlotBackpack(pos))
  822. {
  823. auto backpackPos = pos - ArtifactPosition::BACKPACK_START;
  824. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  825. return nullptr;
  826. else
  827. return &artifactsInBackpack[backpackPos];
  828. }
  829. return nullptr;
  830. }
  831. bool CArtifactSet::isPositionFree(const ArtifactPosition & pos, bool onlyLockCheck) const
  832. {
  833. if(const ArtSlotInfo *s = getSlot(pos))
  834. return (onlyLockCheck || !s->artifact) && !s->locked;
  835. return true; //no slot means not used
  836. }
  837. void CArtifactSet::setNewArtSlot(const ArtifactPosition & slot, ConstTransitivePtr<CArtifactInstance> art, bool locked)
  838. {
  839. assert(!vstd::contains(artifactsWorn, slot));
  840. ArtSlotInfo * slotInfo;
  841. if(slot == ArtifactPosition::TRANSITION_POS)
  842. {
  843. // Always add to the end. Always take from the beginning.
  844. artifactsTransitionPos.emplace_back();
  845. slotInfo = &artifactsTransitionPos.back();
  846. }
  847. else if(ArtifactUtils::isSlotEquipment(slot))
  848. {
  849. slotInfo = &artifactsWorn[slot];
  850. }
  851. else
  852. {
  853. auto position = artifactsInBackpack.begin() + slot - ArtifactPosition::BACKPACK_START;
  854. slotInfo = &(*artifactsInBackpack.emplace(position, ArtSlotInfo()));
  855. }
  856. slotInfo->artifact = art;
  857. slotInfo->locked = locked;
  858. }
  859. void CArtifactSet::eraseArtSlot(const ArtifactPosition & slot)
  860. {
  861. if(slot == ArtifactPosition::TRANSITION_POS)
  862. {
  863. assert(!artifactsTransitionPos.empty());
  864. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  865. }
  866. else if(ArtifactUtils::isSlotBackpack(slot))
  867. {
  868. auto backpackSlot = ArtifactPosition(slot - ArtifactPosition::BACKPACK_START);
  869. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  870. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  871. }
  872. else
  873. {
  874. artifactsWorn.erase(slot);
  875. }
  876. }
  877. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  878. {
  879. for(auto & elem : artifactsWorn)
  880. if(elem.second.artifact && !elem.second.locked)
  881. node->attachTo(*elem.second.artifact);
  882. }
  883. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  884. {
  885. //todo: creature and commander artifacts
  886. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  887. return;
  888. if(!handler.saving)
  889. {
  890. assert(map);
  891. artifactsInBackpack.clear();
  892. artifactsWorn.clear();
  893. }
  894. auto s = handler.enterStruct(fieldName);
  895. switch(bearerType())
  896. {
  897. case ArtBearer::HERO:
  898. serializeJsonHero(handler, map);
  899. break;
  900. case ArtBearer::CREATURE:
  901. serializeJsonCreature(handler, map);
  902. break;
  903. case ArtBearer::COMMANDER:
  904. serializeJsonCommander(handler, map);
  905. break;
  906. default:
  907. assert(false);
  908. break;
  909. }
  910. }
  911. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  912. {
  913. for(const auto & slot : ArtifactUtils::allWornSlots())
  914. {
  915. serializeJsonSlot(handler, slot, map);
  916. }
  917. std::vector<ArtifactID> backpackTemp;
  918. if(handler.saving)
  919. {
  920. backpackTemp.reserve(artifactsInBackpack.size());
  921. for(const ArtSlotInfo & info : artifactsInBackpack)
  922. backpackTemp.push_back(info.artifact->getTypeId());
  923. }
  924. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  925. if(!handler.saving)
  926. {
  927. for(const ArtifactID & artifactID : backpackTemp)
  928. {
  929. auto * artifact = ArtifactUtils::createArtifact(map, artifactID);
  930. auto slot = ArtifactPosition::BACKPACK_START + artifactsInBackpack.size();
  931. if(artifact->artType->canBePutAt(this, slot))
  932. {
  933. auto artsMap = putArtifact(slot, artifact);
  934. artifact->addPlacementMap(artsMap);
  935. }
  936. }
  937. }
  938. }
  939. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  940. {
  941. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  942. }
  943. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  944. {
  945. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  946. }
  947. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  948. {
  949. ArtifactID artifactID;
  950. if(handler.saving)
  951. {
  952. const ArtSlotInfo * info = getSlot(slot);
  953. if(info != nullptr && !info->locked)
  954. {
  955. artifactID = info->artifact->getTypeId();
  956. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  957. }
  958. }
  959. else
  960. {
  961. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  962. if(artifactID != ArtifactID::NONE)
  963. {
  964. auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
  965. if(artifact->artType->canBePutAt(this, slot))
  966. {
  967. auto artsMap = putArtifact(slot, artifact);
  968. artifact->addPlacementMap(artsMap);
  969. }
  970. else
  971. {
  972. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  973. }
  974. }
  975. }
  976. }
  977. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer):
  978. Bearer(Bearer)
  979. {
  980. }
  981. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  982. {
  983. return this->Bearer;
  984. }
  985. VCMI_LIB_NAMESPACE_END