CArtHandler.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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 "filesystem/Filesystem.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "CModHandler.h"
  16. #include "CCreatureHandler.h"
  17. #include "spells/CSpellHandler.h"
  18. #include "mapObjects/MapObjects.h"
  19. #include "NetPacksBase.h"
  20. #include "StringConstants.h"
  21. #include "CRandomGenerator.h"
  22. #include "mapObjects/CObjectClassesHandler.h"
  23. #include "mapping/CMap.h"
  24. #include "serializer/JsonSerializeFormat.h"
  25. // Note: list must match entries in ArtTraits.txt
  26. #define ART_POS_LIST \
  27. ART_POS(SPELLBOOK) \
  28. ART_POS(MACH4) \
  29. ART_POS(MACH3) \
  30. ART_POS(MACH2) \
  31. ART_POS(MACH1) \
  32. ART_POS(MISC5) \
  33. ART_POS(MISC4) \
  34. ART_POS(MISC3) \
  35. ART_POS(MISC2) \
  36. ART_POS(MISC1) \
  37. ART_POS(FEET) \
  38. ART_POS(LEFT_RING) \
  39. ART_POS(RIGHT_RING) \
  40. ART_POS(TORSO) \
  41. ART_POS(LEFT_HAND) \
  42. ART_POS(RIGHT_HAND) \
  43. ART_POS(NECK) \
  44. ART_POS(SHOULDERS) \
  45. ART_POS(HEAD)
  46. VCMI_LIB_NAMESPACE_BEGIN
  47. int32_t CArtifact::getIndex() const
  48. {
  49. return id.toEnum();
  50. }
  51. int32_t CArtifact::getIconIndex() const
  52. {
  53. return iconIndex;
  54. }
  55. std::string CArtifact::getJsonKey() const
  56. {
  57. return modScope + ':' + identifier;
  58. }
  59. void CArtifact::registerIcons(const IconRegistar & cb) const
  60. {
  61. cb(getIconIndex(), 0, "ARTIFACT", image);
  62. cb(getIconIndex(), 0, "ARTIFACTLARGE", large);
  63. }
  64. ArtifactID CArtifact::getId() const
  65. {
  66. return id;
  67. }
  68. const IBonusBearer * CArtifact::accessBonuses() const
  69. {
  70. return this;
  71. }
  72. std::string CArtifact::getDescriptionTranslated() const
  73. {
  74. return VLC->generaltexth->translate(getDescriptionTextID());
  75. }
  76. std::string CArtifact::getEventTranslated() const
  77. {
  78. return VLC->generaltexth->translate(getEventTextID());
  79. }
  80. std::string CArtifact::getNameTranslated() const
  81. {
  82. return VLC->generaltexth->translate(getNameTextID());
  83. }
  84. std::string CArtifact::getDescriptionTextID() const
  85. {
  86. return TextIdentifier("artifact", modScope, identifier, "description").get();
  87. }
  88. std::string CArtifact::getEventTextID() const
  89. {
  90. return TextIdentifier("artifact", modScope, identifier, "event").get();
  91. }
  92. std::string CArtifact::getNameTextID() const
  93. {
  94. return TextIdentifier("artifact", modScope, identifier, "name").get();
  95. }
  96. uint32_t CArtifact::getPrice() const
  97. {
  98. return price;
  99. }
  100. CreatureID CArtifact::getWarMachine() const
  101. {
  102. return warMachine;
  103. }
  104. bool CArtifact::isBig() const
  105. {
  106. return warMachine != CreatureID::NONE;
  107. }
  108. bool CArtifact::isTradable() const
  109. {
  110. switch(id)
  111. {
  112. case ArtifactID::SPELLBOOK:
  113. case ArtifactID::GRAIL:
  114. return false;
  115. default:
  116. return !isBig();
  117. }
  118. }
  119. CArtifact::CArtifact()
  120. {
  121. setNodeType(ARTIFACT);
  122. possibleSlots[ArtBearer::HERO]; //we want to generate map entry even if it will be empty
  123. possibleSlots[ArtBearer::CREATURE]; //we want to generate map entry even if it will be empty
  124. possibleSlots[ArtBearer::COMMANDER];
  125. iconIndex = ArtifactID::NONE;
  126. price = 0;
  127. aClass = ART_SPECIAL;
  128. }
  129. CArtifact::~CArtifact()
  130. {
  131. }
  132. int CArtifact::getArtClassSerial() const
  133. {
  134. if(id == ArtifactID::SPELL_SCROLL)
  135. return 4;
  136. switch(aClass)
  137. {
  138. case ART_TREASURE:
  139. return 0;
  140. case ART_MINOR:
  141. return 1;
  142. case ART_MAJOR:
  143. return 2;
  144. case ART_RELIC:
  145. return 3;
  146. case ART_SPECIAL:
  147. return 5;
  148. }
  149. return -1;
  150. }
  151. std::string CArtifact::nodeName() const
  152. {
  153. return "Artifact: " + getNameTranslated();
  154. }
  155. void CArtifact::addNewBonus(const std::shared_ptr<Bonus>& b)
  156. {
  157. b->source = Bonus::ARTIFACT;
  158. b->duration = Bonus::PERMANENT;
  159. b->description = getNameTranslated();
  160. CBonusSystemNode::addNewBonus(b);
  161. }
  162. void CArtifact::updateFrom(const JsonNode& data)
  163. {
  164. //TODO:CArtifact::updateFrom
  165. }
  166. void CArtifact::serializeJson(JsonSerializeFormat & handler)
  167. {
  168. }
  169. void CGrowingArtifact::levelUpArtifact (CArtifactInstance * art)
  170. {
  171. auto b = std::make_shared<Bonus>();
  172. b->type = Bonus::LEVEL_COUNTER;
  173. b->val = 1;
  174. b->duration = Bonus::COMMANDER_KILLED;
  175. art->accumulateBonus(b);
  176. for (auto bonus : bonusesPerLevel)
  177. {
  178. if (art->valOfBonuses(Bonus::LEVEL_COUNTER) % bonus.first == 0) //every n levels
  179. {
  180. art->accumulateBonus(std::make_shared<Bonus>(bonus.second));
  181. }
  182. }
  183. for (auto bonus : thresholdBonuses)
  184. {
  185. if (art->valOfBonuses(Bonus::LEVEL_COUNTER) == bonus.first) //every n levels
  186. {
  187. art->addNewBonus(std::make_shared<Bonus>(bonus.second));
  188. }
  189. }
  190. }
  191. CArtHandler::CArtHandler()
  192. {
  193. }
  194. CArtHandler::~CArtHandler() = default;
  195. std::vector<JsonNode> CArtHandler::loadLegacyData(size_t dataSize)
  196. {
  197. objects.resize(dataSize);
  198. std::vector<JsonNode> h3Data;
  199. h3Data.reserve(dataSize);
  200. #define ART_POS(x) #x ,
  201. const std::vector<std::string> artSlots = { ART_POS_LIST };
  202. #undef ART_POS
  203. static std::map<char, std::string> classes =
  204. {{'S',"SPECIAL"}, {'T',"TREASURE"},{'N',"MINOR"},{'J',"MAJOR"},{'R',"RELIC"},};
  205. CLegacyConfigParser parser("DATA/ARTRAITS.TXT");
  206. CLegacyConfigParser events("DATA/ARTEVENT.TXT");
  207. parser.endLine(); // header
  208. parser.endLine();
  209. for (size_t i = 0; i < dataSize; i++)
  210. {
  211. JsonNode artData;
  212. artData["text"]["name"].String() = parser.readString();
  213. artData["text"]["event"].String() = events.readString();
  214. artData["value"].Float() = parser.readNumber();
  215. for(auto & artSlot : artSlots)
  216. {
  217. if(parser.readString() == "x")
  218. {
  219. artData["slot"].Vector().push_back(JsonNode());
  220. artData["slot"].Vector().back().String() = artSlot;
  221. }
  222. }
  223. artData["class"].String() = classes[parser.readString()[0]];
  224. artData["text"]["description"].String() = parser.readString();
  225. parser.endLine();
  226. events.endLine();
  227. h3Data.push_back(artData);
  228. }
  229. return h3Data;
  230. }
  231. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  232. {
  233. auto object = loadFromJson(scope, data, name, objects.size());
  234. object->iconIndex = object->getIndex() + 5;
  235. objects.push_back(object);
  236. registerObject(scope, "artifact", name, object->id);
  237. }
  238. void CArtHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  239. {
  240. auto object = loadFromJson(scope, data, name, index);
  241. object->iconIndex = object->getIndex();
  242. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  243. objects[index] = object;
  244. registerObject(scope, "artifact", name, object->id);
  245. }
  246. const std::vector<std::string> & CArtHandler::getTypeNames() const
  247. {
  248. static const std::vector<std::string> typeNames = { "artifact" };
  249. return typeNames;
  250. }
  251. CArtifact * CArtHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  252. {
  253. assert(identifier.find(':') == std::string::npos);
  254. assert(!scope.empty());
  255. CArtifact * art;
  256. if(!VLC->modh->modules.COMMANDERS || node["growing"].isNull())
  257. {
  258. art = new CArtifact();
  259. }
  260. else
  261. {
  262. auto growing = new CGrowingArtifact();
  263. loadGrowingArt(growing, node);
  264. art = growing;
  265. }
  266. art->id = ArtifactID(index);
  267. art->identifier = identifier;
  268. art->modScope = scope;
  269. const JsonNode & text = node["text"];
  270. VLC->generaltexth->registerString(art->getNameTextID(), text["name"].String());
  271. VLC->generaltexth->registerString(art->getDescriptionTextID(), text["description"].String());
  272. VLC->generaltexth->registerString(art->getEventTextID(), text["event"].String());
  273. const JsonNode & graphics = node["graphics"];
  274. art->image = graphics["image"].String();
  275. if(!graphics["large"].isNull())
  276. art->large = graphics["large"].String();
  277. else
  278. art->large = art->image;
  279. art->advMapDef = graphics["map"].String();
  280. art->price = static_cast<ui32>(node["value"].Float());
  281. loadSlots(art, node);
  282. loadClass(art, node);
  283. loadType(art, node);
  284. loadComponents(art, node);
  285. for(auto b : node["bonuses"].Vector())
  286. {
  287. auto bonus = JsonUtils::parseBonus(b);
  288. art->addNewBonus(bonus);
  289. }
  290. const JsonNode & warMachine = node["warMachine"];
  291. if(warMachine.getType() == JsonNode::JsonType::DATA_STRING && !warMachine.String().empty())
  292. {
  293. VLC->modh->identifiers.requestIdentifier("creature", warMachine, [=](si32 id)
  294. {
  295. art->warMachine = CreatureID(id);
  296. //this assumes that creature object is stored before registration
  297. VLC->creh->objects.at(id)->warMachine = art->id;
  298. });
  299. }
  300. VLC->modh->identifiers.requestIdentifier(scope, "object", "artifact", [=](si32 index)
  301. {
  302. JsonNode conf;
  303. conf.setMeta(scope);
  304. VLC->objtypeh->loadSubObject(art->identifier, conf, Obj::ARTIFACT, art->getIndex());
  305. if(!art->advMapDef.empty())
  306. {
  307. JsonNode templ;
  308. templ["animation"].String() = art->advMapDef;
  309. templ.setMeta(scope);
  310. // add new template.
  311. // Necessary for objects added via mods that don't have any templates in H3
  312. VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->addTemplate(templ);
  313. }
  314. // object does not have any templates - this is not usable object (e.g. pseudo-art like lock)
  315. if(VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, art->getIndex())->getTemplates().empty())
  316. VLC->objtypeh->removeSubObject(Obj::ARTIFACT, art->getIndex());
  317. });
  318. return art;
  319. }
  320. ArtifactPosition::ArtifactPosition(std::string slotName):
  321. num(ArtifactPosition::PRE_FIRST)
  322. {
  323. #define ART_POS(x) { #x, ArtifactPosition::x },
  324. static const std::map<std::string, ArtifactPosition> artifactPositionMap = { ART_POS_LIST };
  325. #undef ART_POS
  326. auto it = artifactPositionMap.find (slotName);
  327. if (it != artifactPositionMap.end())
  328. num = it->second;
  329. else
  330. logMod->warn("Warning! Artifact slot %s not recognized!", slotName);
  331. }
  332. void CArtHandler::addSlot(CArtifact * art, const std::string & slotID)
  333. {
  334. static const std::vector<ArtifactPosition> miscSlots =
  335. {
  336. ArtifactPosition::MISC1, ArtifactPosition::MISC2, ArtifactPosition::MISC3, ArtifactPosition::MISC4, ArtifactPosition::MISC5
  337. };
  338. static const std::vector<ArtifactPosition> ringSlots =
  339. {
  340. ArtifactPosition::LEFT_RING, ArtifactPosition::RIGHT_RING
  341. };
  342. if (slotID == "MISC")
  343. {
  344. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], miscSlots);
  345. }
  346. else if (slotID == "RING")
  347. {
  348. vstd::concatenate(art->possibleSlots[ArtBearer::HERO], ringSlots);
  349. }
  350. else
  351. {
  352. auto slot = ArtifactPosition(slotID);
  353. if (slot != ArtifactPosition::PRE_FIRST)
  354. art->possibleSlots[ArtBearer::HERO].push_back (slot);
  355. }
  356. }
  357. void CArtHandler::loadSlots(CArtifact * art, const JsonNode & node)
  358. {
  359. if (!node["slot"].isNull()) //we assume non-hero slots are irrelevant?
  360. {
  361. if (node["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  362. addSlot(art, node["slot"].String());
  363. else
  364. {
  365. for (const JsonNode & slot : node["slot"].Vector())
  366. addSlot(art, slot.String());
  367. }
  368. }
  369. }
  370. CArtifact::EartClass CArtHandler::stringToClass(std::string className)
  371. {
  372. static const std::map<std::string, CArtifact::EartClass> artifactClassMap =
  373. {
  374. {"TREASURE", CArtifact::ART_TREASURE},
  375. {"MINOR", CArtifact::ART_MINOR},
  376. {"MAJOR", CArtifact::ART_MAJOR},
  377. {"RELIC", CArtifact::ART_RELIC},
  378. {"SPECIAL", CArtifact::ART_SPECIAL}
  379. };
  380. auto it = artifactClassMap.find (className);
  381. if (it != artifactClassMap.end())
  382. return it->second;
  383. logMod->warn("Warning! Artifact rarity %s not recognized!", className);
  384. return CArtifact::ART_SPECIAL;
  385. }
  386. void CArtHandler::loadClass(CArtifact * art, const JsonNode & node)
  387. {
  388. art->aClass = stringToClass(node["class"].String());
  389. }
  390. void CArtHandler::loadType(CArtifact * art, const JsonNode & node)
  391. {
  392. #define ART_BEARER(x) { #x, ArtBearer::x },
  393. static const std::map<std::string, int> artifactBearerMap = { ART_BEARER_LIST };
  394. #undef ART_BEARER
  395. for (const JsonNode & b : node["type"].Vector())
  396. {
  397. auto it = artifactBearerMap.find (b.String());
  398. if (it != artifactBearerMap.end())
  399. {
  400. int bearerType = it->second;
  401. switch (bearerType)
  402. {
  403. case ArtBearer::HERO://TODO: allow arts having several possible bearers
  404. break;
  405. case ArtBearer::COMMANDER:
  406. makeItCommanderArt (art); //original artifacts should have only one bearer type
  407. break;
  408. case ArtBearer::CREATURE:
  409. makeItCreatureArt (art);
  410. break;
  411. }
  412. }
  413. else
  414. logMod->warn("Warning! Artifact type %s not recognized!", b.String());
  415. }
  416. }
  417. void CArtHandler::loadComponents(CArtifact * art, const JsonNode & node)
  418. {
  419. if (!node["components"].isNull())
  420. {
  421. art->constituents.reset(new std::vector<CArtifact *>());
  422. for (auto component : node["components"].Vector())
  423. {
  424. VLC->modh->identifiers.requestIdentifier("artifact", component, [=](si32 id)
  425. {
  426. // when this code is called both combinational art as well as component are loaded
  427. // so it is safe to access any of them
  428. art->constituents->push_back(objects[id]);
  429. objects[id]->constituentOf.push_back(art);
  430. });
  431. }
  432. }
  433. }
  434. void CArtHandler::loadGrowingArt(CGrowingArtifact * art, const JsonNode & node)
  435. {
  436. for (auto b : node["growing"]["bonusesPerLevel"].Vector())
  437. {
  438. art->bonusesPerLevel.push_back(std::pair <ui16, Bonus>((ui16)b["level"].Float(), Bonus()));
  439. JsonUtils::parseBonus(b["bonus"], &art->bonusesPerLevel.back().second);
  440. }
  441. for (auto b : node["growing"]["thresholdBonuses"].Vector())
  442. {
  443. art->thresholdBonuses.push_back(std::pair <ui16, Bonus>((ui16)b["level"].Float(), Bonus()));
  444. JsonUtils::parseBonus(b["bonus"], &art->thresholdBonuses.back().second);
  445. }
  446. }
  447. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags, std::function<bool(ArtifactID)> accepts)
  448. {
  449. auto getAllowedArts = [&](std::vector<ConstTransitivePtr<CArtifact> > &out, std::vector<CArtifact*> *arts, CArtifact::EartClass flag)
  450. {
  451. if (arts->empty()) //restock available arts
  452. fillList(*arts, flag);
  453. for (auto & arts_i : *arts)
  454. {
  455. if (accepts(arts_i->id))
  456. {
  457. CArtifact *art = arts_i;
  458. out.push_back(art);
  459. }
  460. }
  461. };
  462. auto getAllowed = [&](std::vector<ConstTransitivePtr<CArtifact> > &out)
  463. {
  464. if (flags & CArtifact::ART_TREASURE)
  465. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  466. if (flags & CArtifact::ART_MINOR)
  467. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  468. if (flags & CArtifact::ART_MAJOR)
  469. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  470. if (flags & CArtifact::ART_RELIC)
  471. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  472. if (!out.size()) //no artifact of specified rarity, we need to take another one
  473. {
  474. getAllowedArts (out, &treasures, CArtifact::ART_TREASURE);
  475. getAllowedArts (out, &minors, CArtifact::ART_MINOR);
  476. getAllowedArts (out, &majors, CArtifact::ART_MAJOR);
  477. getAllowedArts (out, &relics, CArtifact::ART_RELIC);
  478. }
  479. if (!out.size()) //no arts are available at all
  480. {
  481. out.resize (64);
  482. std::fill_n (out.begin(), 64, objects[2]); //Give Grail - this can't be banned (hopefully)
  483. }
  484. };
  485. std::vector<ConstTransitivePtr<CArtifact> > out;
  486. getAllowed(out);
  487. ArtifactID artID = (*RandomGeneratorUtil::nextItem(out, rand))->id;
  488. erasePickedArt(artID);
  489. return artID;
  490. }
  491. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, std::function<bool(ArtifactID)> accepts)
  492. {
  493. return pickRandomArtifact(rand, 0xff, accepts);
  494. }
  495. ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags)
  496. {
  497. return pickRandomArtifact(rand, flags, [](ArtifactID){ return true;});
  498. }
  499. void CArtHandler::makeItCreatureArt(CArtifact * a, bool onlyCreature)
  500. {
  501. if (onlyCreature)
  502. {
  503. a->possibleSlots[ArtBearer::HERO].clear();
  504. a->possibleSlots[ArtBearer::COMMANDER].clear();
  505. }
  506. a->possibleSlots[ArtBearer::CREATURE].push_back(ArtifactPosition::CREATURE_SLOT);
  507. }
  508. void CArtHandler::makeItCommanderArt(CArtifact * a, bool onlyCommander)
  509. {
  510. if (onlyCommander)
  511. {
  512. a->possibleSlots[ArtBearer::HERO].clear();
  513. a->possibleSlots[ArtBearer::CREATURE].clear();
  514. }
  515. for (int i = ArtifactPosition::COMMANDER1; i <= ArtifactPosition::COMMANDER6; ++i)
  516. a->possibleSlots[ArtBearer::COMMANDER].push_back(ArtifactPosition(i));
  517. }
  518. bool CArtHandler::legalArtifact(ArtifactID id)
  519. {
  520. auto art = objects[id];
  521. //assert ( (!art->constituents) || art->constituents->size() ); //artifacts is not combined or has some components
  522. return ((art->possibleSlots[ArtBearer::HERO].size() ||
  523. (art->possibleSlots[ArtBearer::COMMANDER].size() && VLC->modh->modules.COMMANDERS) ||
  524. (art->possibleSlots[ArtBearer::CREATURE].size() && VLC->modh->modules.STACK_ARTIFACT)) &&
  525. !(art->constituents) && //no combo artifacts spawning
  526. art->aClass >= CArtifact::ART_TREASURE &&
  527. art->aClass <= CArtifact::ART_RELIC);
  528. }
  529. void CArtHandler::initAllowedArtifactsList(const std::vector<bool> &allowed)
  530. {
  531. allowedArtifacts.clear();
  532. treasures.clear();
  533. minors.clear();
  534. majors.clear();
  535. relics.clear();
  536. for (ArtifactID i=ArtifactID::SPELLBOOK; i<ArtifactID::ART_SELECTION; i.advance(1))
  537. {
  538. //check artifacts allowed on a map
  539. //TODO: This line will be different when custom map format is implemented
  540. if (allowed[i] && legalArtifact(i))
  541. allowedArtifacts.push_back(objects[i]);
  542. }
  543. for (ArtifactID i = ArtifactID::ART_SELECTION; i<ArtifactID((si32)objects.size()); i.advance(1)) //try to allow all artifacts added by mods
  544. {
  545. if (legalArtifact(ArtifactID(i)))
  546. allowedArtifacts.push_back(objects[i]);
  547. //keep im mind that artifact can be worn by more than one type of bearer
  548. }
  549. }
  550. std::vector<bool> CArtHandler::getDefaultAllowed() const
  551. {
  552. std::vector<bool> allowedArtifacts;
  553. allowedArtifacts.resize(127, true);
  554. allowedArtifacts.resize(141, false);
  555. allowedArtifacts.resize(size(), true);
  556. return allowedArtifacts;
  557. }
  558. void CArtHandler::erasePickedArt(ArtifactID id)
  559. {
  560. CArtifact *art = objects[id];
  561. if(auto artifactList = listFromClass(art->aClass))
  562. {
  563. if(artifactList->empty())
  564. fillList(*artifactList, art->aClass);
  565. auto itr = vstd::find(*artifactList, art);
  566. if(itr != artifactList->end())
  567. {
  568. artifactList->erase(itr);
  569. }
  570. else
  571. logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated());
  572. }
  573. else
  574. logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated());
  575. }
  576. boost::optional<std::vector<CArtifact*>&> CArtHandler::listFromClass( CArtifact::EartClass artifactClass )
  577. {
  578. switch(artifactClass)
  579. {
  580. case CArtifact::ART_TREASURE:
  581. return treasures;
  582. case CArtifact::ART_MINOR:
  583. return minors;
  584. case CArtifact::ART_MAJOR:
  585. return majors;
  586. case CArtifact::ART_RELIC:
  587. return relics;
  588. default: //special artifacts should not be erased
  589. return boost::optional<std::vector<CArtifact*>&>();
  590. }
  591. }
  592. void CArtHandler::fillList( std::vector<CArtifact*> &listToBeFilled, CArtifact::EartClass artifactClass )
  593. {
  594. assert(listToBeFilled.empty());
  595. for (auto & elem : allowedArtifacts)
  596. {
  597. if (elem->aClass == artifactClass)
  598. listToBeFilled.push_back(elem);
  599. }
  600. }
  601. void CArtHandler::afterLoadFinalization()
  602. {
  603. //All artifacts have their id, so we can properly update their bonuses' source ids.
  604. for(auto &art : objects)
  605. {
  606. for(auto &bonus : art->getExportedBonusList())
  607. {
  608. assert(art == objects[art->id]);
  609. assert(bonus->source == Bonus::ARTIFACT);
  610. bonus->sid = art->id;
  611. }
  612. }
  613. CBonusSystemNode::treeHasChanged();
  614. }
  615. CArtifactInstance::CArtifactInstance()
  616. {
  617. init();
  618. }
  619. CArtifactInstance::CArtifactInstance( CArtifact *Art)
  620. {
  621. init();
  622. setType(Art);
  623. }
  624. void CArtifactInstance::setType( CArtifact *Art )
  625. {
  626. artType = Art;
  627. attachTo(*Art);
  628. }
  629. std::string CArtifactInstance::nodeName() const
  630. {
  631. return "Artifact instance of " + (artType ? artType->getJsonKey() : std::string("uninitialized")) + " type";
  632. }
  633. CArtifactInstance *CArtifactInstance::createScroll(SpellID sid)
  634. {
  635. auto ret = new CArtifactInstance(VLC->arth->objects[ArtifactID::SPELL_SCROLL]);
  636. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::SPELL, Bonus::ARTIFACT_INSTANCE, -1, ArtifactID::SPELL_SCROLL, sid);
  637. ret->addNewBonus(b);
  638. return ret;
  639. }
  640. void CArtifactInstance::init()
  641. {
  642. id = ArtifactInstanceID();
  643. id = static_cast<ArtifactInstanceID>(ArtifactID::NONE); //to be randomized
  644. setNodeType(ARTIFACT_INSTANCE);
  645. }
  646. std::string CArtifactInstance::getEffectiveDescription(const CGHeroInstance * hero) const
  647. {
  648. std::string text = artType->getDescriptionTranslated();
  649. if (!vstd::contains(text, '{'))
  650. text = '{' + artType->getNameTranslated() + "}\n\n" + text; //workaround for new artifacts with single name, turns it to H3-style
  651. if(artType->getId() == ArtifactID::SPELL_SCROLL)
  652. {
  653. // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll.
  654. // so we want to replace text in [...] with a spell name
  655. // however other language versions don't have name placeholder at all, so we have to be careful
  656. SpellID spellID = getGivenSpellID();
  657. size_t nameStart = text.find_first_of('[');
  658. size_t nameEnd = text.find_first_of(']', nameStart);
  659. if(spellID.getNum() >= 0)
  660. {
  661. if(nameStart != std::string::npos && nameEnd != std::string::npos)
  662. text = text.replace(nameStart, nameEnd - nameStart + 1, spellID.toSpell(VLC->spells())->getNameTranslated());
  663. }
  664. }
  665. else if(hero && artType->constituentOf.size()) //display info about set
  666. {
  667. std::string artList;
  668. auto combinedArt = artType->constituentOf[0];
  669. text += "\n\n";
  670. text += "{" + combinedArt->getNameTranslated() + "}";
  671. int wornArtifacts = 0;
  672. for(auto a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set?
  673. {
  674. artList += "\n" + a->getNameTranslated();
  675. if (hero->hasArt(a->getId(), true))
  676. wornArtifacts++;
  677. }
  678. text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " +
  679. boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList;
  680. //TODO: fancy colors and fonts for this text
  681. }
  682. return text;
  683. }
  684. ArtifactPosition CArtifactInstance::firstAvailableSlot(const CArtifactSet *h) const
  685. {
  686. for(auto slot : artType->possibleSlots.at(h->bearerType()))
  687. {
  688. if(canBePutAt(h, slot)) //if(artType->fitsAt(h->artifWorn, slot))
  689. {
  690. //we've found a free suitable slot.
  691. return slot;
  692. }
  693. }
  694. //if haven't find proper slot, use backpack
  695. return firstBackpackSlot(h);
  696. }
  697. ArtifactPosition CArtifactInstance::firstBackpackSlot(const CArtifactSet *h) const
  698. {
  699. if(!artType->isBig()) //discard big artifact
  700. return ArtifactPosition(
  701. GameConstants::BACKPACK_START + (si32)h->artifactsInBackpack.size());
  702. return ArtifactPosition::PRE_FIRST;
  703. }
  704. bool CArtifactInstance::canBePutAt(const ArtifactLocation & al, bool assumeDestRemoved) const
  705. {
  706. return canBePutAt(al.getHolderArtSet(), al.slot, assumeDestRemoved);
  707. }
  708. bool CArtifactInstance::canBePutAt(const CArtifactSet *artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  709. {
  710. if(slot == ArtifactPosition::TRANSITION_POS)
  711. {
  712. return true;
  713. }
  714. if(ArtifactUtils::isSlotBackpack(slot))
  715. {
  716. if(artType->isBig())
  717. return false;
  718. //TODO backpack limit
  719. return true;
  720. }
  721. auto possibleSlots = artType->possibleSlots.find(artSet->bearerType());
  722. if(possibleSlots == artType->possibleSlots.end())
  723. {
  724. logMod->warn("Warning: artifact %s doesn't have defined allowed slots for bearer of type %s", artType->getNameTranslated(), artSet->bearerType());
  725. return false;
  726. }
  727. if(!vstd::contains(possibleSlots->second, slot))
  728. return false;
  729. return artSet->isPositionFree(slot, assumeDestRemoved);
  730. }
  731. void CArtifactInstance::putAt(ArtifactLocation al)
  732. {
  733. assert(canBePutAt(al));
  734. al.getHolderArtSet()->setNewArtSlot(al.slot, this, false);
  735. if(ArtifactUtils::isSlotEquipment(al.slot))
  736. al.getHolderNode()->attachTo(*this);
  737. }
  738. void CArtifactInstance::removeFrom(ArtifactLocation al)
  739. {
  740. assert(al.getHolderArtSet()->getArt(al.slot) == this);
  741. al.getHolderArtSet()->eraseArtSlot(al.slot);
  742. if(ArtifactUtils::isSlotEquipment(al.slot))
  743. al.getHolderNode()->detachFrom(*this);
  744. }
  745. bool CArtifactInstance::canBeDisassembled() const
  746. {
  747. return bool(artType->constituents);
  748. }
  749. std::vector<const CArtifact *> CArtifactInstance::assemblyPossibilities(const CArtifactSet * h, bool equipped) const
  750. {
  751. std::vector<const CArtifact *> ret;
  752. if(artType->constituents) //combined artifact already: no combining of combined artifacts... for now.
  753. return ret;
  754. for(const auto * artifact : artType->constituentOf)
  755. {
  756. assert(artifact->constituents);
  757. bool possible = true;
  758. for(const auto * constituent : *artifact->constituents) //check if all constituents are available
  759. {
  760. if(equipped)
  761. {
  762. // Search for equipped arts
  763. if (!h->hasArt(constituent->getId(), true, false, false))
  764. {
  765. possible = false;
  766. break;
  767. }
  768. }
  769. else
  770. {
  771. // Search in backpack
  772. if(!h->hasArtBackpack(constituent->getId()))
  773. {
  774. possible = false;
  775. break;
  776. }
  777. }
  778. }
  779. if(possible)
  780. ret.push_back(artifact);
  781. }
  782. return ret;
  783. }
  784. void CArtifactInstance::move(ArtifactLocation src, ArtifactLocation dst)
  785. {
  786. removeFrom(src);
  787. putAt(dst);
  788. }
  789. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(CArtifact *Art)
  790. {
  791. if(!Art->constituents)
  792. {
  793. auto ret = new CArtifactInstance(Art);
  794. if (dynamic_cast<CGrowingArtifact *>(Art))
  795. {
  796. auto bonus = std::make_shared<Bonus>();
  797. bonus->type = Bonus::LEVEL_COUNTER;
  798. bonus->val = 0;
  799. ret->addNewBonus (bonus);
  800. }
  801. return ret;
  802. }
  803. else
  804. {
  805. auto ret = new CCombinedArtifactInstance(Art);
  806. ret->createConstituents();
  807. return ret;
  808. }
  809. }
  810. CArtifactInstance * CArtifactInstance::createNewArtifactInstance(ArtifactID aid)
  811. {
  812. return createNewArtifactInstance(VLC->arth->objects[aid]);
  813. }
  814. CArtifactInstance * CArtifactInstance::createArtifact(CMap * map, ArtifactID aid, int spellID)
  815. {
  816. CArtifactInstance * a = nullptr;
  817. if(aid >= 0)
  818. {
  819. if(spellID < 0)
  820. {
  821. a = CArtifactInstance::createNewArtifactInstance(aid);
  822. }
  823. else
  824. {
  825. a = CArtifactInstance::createScroll(SpellID(spellID));
  826. }
  827. }
  828. else //FIXME: create combined artifact instance for random combined artifacts, just in case
  829. {
  830. a = new CArtifactInstance(); //random, empty
  831. }
  832. map->addNewArtifactInstance(a);
  833. //TODO make it nicer
  834. if(a->artType && (!!a->artType->constituents))
  835. {
  836. CCombinedArtifactInstance * comb = dynamic_cast<CCombinedArtifactInstance *>(a);
  837. for(CCombinedArtifactInstance::ConstituentInfo & ci : comb->constituentsInfo)
  838. {
  839. map->addNewArtifactInstance(ci.art);
  840. }
  841. }
  842. return a;
  843. }
  844. void CArtifactInstance::deserializationFix()
  845. {
  846. setType(artType);
  847. }
  848. SpellID CArtifactInstance::getGivenSpellID() const
  849. {
  850. const auto b = getBonusLocalFirst(Selector::type()(Bonus::SPELL));
  851. if(!b)
  852. {
  853. logMod->warn("Warning: %s doesn't bear any spell!", nodeName());
  854. return SpellID::NONE;
  855. }
  856. return SpellID(b->subtype);
  857. }
  858. bool CArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  859. {
  860. return supposedPart == this;
  861. }
  862. bool CCombinedArtifactInstance::canBePutAt(const CArtifactSet * artSet, ArtifactPosition slot, bool assumeDestRemoved) const
  863. {
  864. if(slot == ArtifactPosition::TRANSITION_POS)
  865. return true;
  866. if(!CArtifactInstance::canBePutAt(artSet, slot, assumeDestRemoved))
  867. return false;
  868. if(ArtifactUtils::isSlotBackpack(slot))
  869. return true; //we can always remove combined art to the backapck
  870. CArtifactFittingSet fittingSet(artSet->bearerType());
  871. fittingSet.artifactsWorn = artSet->artifactsWorn;
  872. auto artToRemove = fittingSet.getArt(slot);
  873. if(assumeDestRemoved && artToRemove)
  874. {
  875. if(artToRemove->canBeDisassembled())
  876. {
  877. auto combinedArtToRemove = dynamic_cast<CCombinedArtifactInstance*>(artToRemove);
  878. for(auto & part : combinedArtToRemove->constituentsInfo)
  879. {
  880. if(ArtifactUtils::isSlotEquipment(part.slot))
  881. {
  882. fittingSet.eraseArtSlot(part.slot);
  883. }
  884. }
  885. }
  886. fittingSet.eraseArtSlot(slot);
  887. }
  888. for(auto & art : constituentsInfo)
  889. {
  890. auto possibleSlot = art.art->firstAvailableSlot(&fittingSet);
  891. if(ArtifactUtils::isSlotEquipment(possibleSlot))
  892. {
  893. fittingSet.setNewArtSlot(possibleSlot, nullptr, true);
  894. }
  895. else
  896. {
  897. return false;
  898. }
  899. }
  900. return true;
  901. }
  902. bool CCombinedArtifactInstance::canBeDisassembled() const
  903. {
  904. return true;
  905. }
  906. CCombinedArtifactInstance::CCombinedArtifactInstance(CArtifact *Art)
  907. : CArtifactInstance(Art) //TODO: seems unused, but need to be written
  908. {
  909. }
  910. CCombinedArtifactInstance::CCombinedArtifactInstance()
  911. {
  912. }
  913. void CCombinedArtifactInstance::createConstituents()
  914. {
  915. assert(artType);
  916. assert(artType->constituents);
  917. for(const CArtifact * art : *artType->constituents)
  918. {
  919. addAsConstituent(CArtifactInstance::createNewArtifactInstance(art->getId()), ArtifactPosition::PRE_FIRST);
  920. }
  921. }
  922. void CCombinedArtifactInstance::addAsConstituent(CArtifactInstance *art, ArtifactPosition slot)
  923. {
  924. assert(vstd::contains_if(*artType->constituents, [=](const CArtifact * constituent){
  925. return constituent->getId() == art->artType->getId();
  926. }));
  927. assert(art->getParentNodes().size() == 1 && art->getParentNodes().front() == art->artType);
  928. constituentsInfo.push_back(ConstituentInfo(art, slot));
  929. attachTo(*art);
  930. }
  931. void CCombinedArtifactInstance::putAt(ArtifactLocation al)
  932. {
  933. if(al.slot == ArtifactPosition::TRANSITION_POS)
  934. {
  935. CArtifactInstance::putAt(al);
  936. }
  937. else if(ArtifactUtils::isSlotBackpack(al.slot))
  938. {
  939. CArtifactInstance::putAt(al);
  940. for(ConstituentInfo &ci : constituentsInfo)
  941. ci.slot = ArtifactPosition::PRE_FIRST;
  942. }
  943. else
  944. {
  945. CArtifactInstance *mainConstituent = figureMainConstituent(al); //it'll be replaced with combined artifact, not a lock
  946. CArtifactInstance::putAt(al); //puts combined art (this)
  947. for(ConstituentInfo &ci : constituentsInfo)
  948. {
  949. if(ci.art != mainConstituent)
  950. {
  951. const ArtifactLocation suggestedPos(al.artHolder, ci.slot);
  952. const bool inActiveSlot = vstd::isbetween(ci.slot, 0, GameConstants::BACKPACK_START);
  953. const bool suggestedPosValid = ci.art->canBePutAt(suggestedPos);
  954. ArtifactPosition pos = ArtifactPosition::PRE_FIRST;
  955. if(inActiveSlot && suggestedPosValid) //there is a valid suggestion where to place lock
  956. pos = ci.slot;
  957. else
  958. ci.slot = pos = ci.art->firstAvailableSlot(al.getHolderArtSet());
  959. assert(!ArtifactUtils::isSlotBackpack(pos));
  960. al.getHolderArtSet()->setNewArtSlot(pos, ci.art, true); //sets as lock
  961. }
  962. else
  963. {
  964. ci.slot = ArtifactPosition::PRE_FIRST;
  965. }
  966. }
  967. }
  968. }
  969. void CCombinedArtifactInstance::removeFrom(ArtifactLocation al)
  970. {
  971. if(ArtifactUtils::isSlotBackpack(al.slot) || al.slot == ArtifactPosition::TRANSITION_POS)
  972. {
  973. CArtifactInstance::removeFrom(al);
  974. }
  975. else
  976. {
  977. for(ConstituentInfo &ci : constituentsInfo)
  978. {
  979. if(ci.slot >= 0)
  980. {
  981. al.getHolderArtSet()->eraseArtSlot(ci.slot);
  982. ci.slot = ArtifactPosition::PRE_FIRST;
  983. }
  984. else
  985. {
  986. //main constituent
  987. CArtifactInstance::removeFrom(al);
  988. }
  989. }
  990. }
  991. }
  992. CArtifactInstance * CCombinedArtifactInstance::figureMainConstituent(const ArtifactLocation al)
  993. {
  994. CArtifactInstance *mainConstituent = nullptr; //it'll be replaced with combined artifact, not a lock
  995. for(ConstituentInfo &ci : constituentsInfo)
  996. if(ci.slot == al.slot)
  997. mainConstituent = ci.art;
  998. if(!mainConstituent)
  999. {
  1000. for(ConstituentInfo &ci : constituentsInfo)
  1001. {
  1002. if(vstd::contains(ci.art->artType->possibleSlots[al.getHolderArtSet()->bearerType()], al.slot))
  1003. {
  1004. mainConstituent = ci.art;
  1005. }
  1006. }
  1007. }
  1008. return mainConstituent;
  1009. }
  1010. void CCombinedArtifactInstance::deserializationFix()
  1011. {
  1012. for(ConstituentInfo &ci : constituentsInfo)
  1013. attachTo(*ci.art);
  1014. }
  1015. bool CCombinedArtifactInstance::isPart(const CArtifactInstance *supposedPart) const
  1016. {
  1017. bool me = CArtifactInstance::isPart(supposedPart);
  1018. if(me)
  1019. return true;
  1020. //check for constituents
  1021. for(const ConstituentInfo &constituent : constituentsInfo)
  1022. if(constituent.art == supposedPart)
  1023. return true;
  1024. return false;
  1025. }
  1026. CCombinedArtifactInstance::ConstituentInfo::ConstituentInfo(CArtifactInstance *Art, ArtifactPosition Slot)
  1027. {
  1028. art = Art;
  1029. slot = Slot;
  1030. }
  1031. bool CCombinedArtifactInstance::ConstituentInfo::operator==(const ConstituentInfo &rhs) const
  1032. {
  1033. return art == rhs.art && slot == rhs.slot;
  1034. }
  1035. CArtifactSet::~CArtifactSet() = default;
  1036. const CArtifactInstance* CArtifactSet::getArt(ArtifactPosition pos, bool excludeLocked) const
  1037. {
  1038. if(const ArtSlotInfo *si = getSlot(pos))
  1039. {
  1040. if(si->artifact && (!excludeLocked || !si->locked))
  1041. return si->artifact;
  1042. }
  1043. return nullptr;
  1044. }
  1045. CArtifactInstance* CArtifactSet::getArt(ArtifactPosition pos, bool excludeLocked)
  1046. {
  1047. return const_cast<CArtifactInstance*>((const_cast<const CArtifactSet*>(this))->getArt(pos, excludeLocked));
  1048. }
  1049. ArtifactPosition CArtifactSet::getArtPos(ArtifactID aid, bool onlyWorn, bool allowLocked) const
  1050. {
  1051. const auto result = getAllArtPositions(aid, onlyWorn, allowLocked, false);
  1052. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1053. }
  1054. ArtifactPosition CArtifactSet::getArtBackpackPos(ArtifactID aid) const
  1055. {
  1056. const auto result = getBackpackArtPositions(aid);
  1057. return result.empty() ? ArtifactPosition{ArtifactPosition::PRE_FIRST} : result[0];
  1058. }
  1059. std::vector<ArtifactPosition> CArtifactSet::getAllArtPositions(ArtifactID aid, bool onlyWorn, bool allowLocked, bool getAll) const
  1060. {
  1061. std::vector<ArtifactPosition> result;
  1062. for(auto & slotInfo : artifactsWorn)
  1063. if(slotInfo.second.artifact->artType->getId() == aid && (allowLocked || !slotInfo.second.locked))
  1064. result.push_back(slotInfo.first);
  1065. if(onlyWorn)
  1066. return result;
  1067. if(!getAll && !result.empty())
  1068. return result;
  1069. auto backpackPositions = getBackpackArtPositions(aid);
  1070. result.insert(result.end(), backpackPositions.begin(), backpackPositions.end());
  1071. return result;
  1072. }
  1073. std::vector<ArtifactPosition> CArtifactSet::getBackpackArtPositions(ArtifactID aid) const
  1074. {
  1075. std::vector<ArtifactPosition> result;
  1076. si32 backpackPosition = GameConstants::BACKPACK_START;
  1077. for(auto & artInfo : artifactsInBackpack)
  1078. {
  1079. auto * art = artInfo.getArt();
  1080. if(art && art->artType->getId() == aid)
  1081. result.emplace_back(backpackPosition);
  1082. backpackPosition++;
  1083. }
  1084. return result;
  1085. }
  1086. ArtifactPosition CArtifactSet::getArtPos(const CArtifactInstance *art) const
  1087. {
  1088. for(auto i : artifactsWorn)
  1089. if(i.second.artifact == art)
  1090. return i.first;
  1091. for(int i = 0; i < artifactsInBackpack.size(); i++)
  1092. if(artifactsInBackpack[i].artifact == art)
  1093. return ArtifactPosition(GameConstants::BACKPACK_START + i);
  1094. return ArtifactPosition::PRE_FIRST;
  1095. }
  1096. const CArtifactInstance * CArtifactSet::getArtByInstanceId( ArtifactInstanceID artInstId ) const
  1097. {
  1098. for(auto i : artifactsWorn)
  1099. if(i.second.artifact->id == artInstId)
  1100. return i.second.artifact;
  1101. for(auto i : artifactsInBackpack)
  1102. if(i.artifact->id == artInstId)
  1103. return i.artifact;
  1104. return nullptr;
  1105. }
  1106. bool CArtifactSet::hasArt(
  1107. ArtifactID aid,
  1108. bool onlyWorn,
  1109. bool searchBackpackAssemblies,
  1110. bool allowLocked) const
  1111. {
  1112. return getArtPosCount(aid, onlyWorn, searchBackpackAssemblies, allowLocked) > 0;
  1113. }
  1114. bool CArtifactSet::hasArtBackpack(ArtifactID aid) const
  1115. {
  1116. return getBackpackArtPositions(aid).size() > 0;
  1117. }
  1118. unsigned CArtifactSet::getArtPosCount(ArtifactID aid, bool onlyWorn, bool searchBackpackAssemblies, bool allowLocked) const
  1119. {
  1120. const auto allPositions = getAllArtPositions(aid, onlyWorn, allowLocked, true);
  1121. if(!allPositions.empty())
  1122. return allPositions.size();
  1123. if(searchBackpackAssemblies && getHiddenArt(aid))
  1124. return 1;
  1125. return 0;
  1126. }
  1127. std::pair<const CCombinedArtifactInstance *, const CArtifactInstance *>
  1128. CArtifactSet::searchForConstituent(ArtifactID aid) const
  1129. {
  1130. for(auto & slot : artifactsInBackpack)
  1131. {
  1132. auto art = slot.artifact;
  1133. if(art->canBeDisassembled())
  1134. {
  1135. auto ass = static_cast<CCombinedArtifactInstance *>(art.get());
  1136. for(auto& ci : ass->constituentsInfo)
  1137. {
  1138. if(ci.art->artType->getId() == aid)
  1139. {
  1140. return {ass, ci.art};
  1141. }
  1142. }
  1143. }
  1144. }
  1145. return {nullptr, nullptr};
  1146. }
  1147. const CArtifactInstance *CArtifactSet::getHiddenArt(ArtifactID aid) const
  1148. {
  1149. return searchForConstituent(aid).second;
  1150. }
  1151. const CCombinedArtifactInstance *CArtifactSet::getAssemblyByConstituent(ArtifactID aid) const
  1152. {
  1153. return searchForConstituent(aid).first;
  1154. }
  1155. const ArtSlotInfo * CArtifactSet::getSlot(ArtifactPosition pos) const
  1156. {
  1157. if(pos == ArtifactPosition::TRANSITION_POS)
  1158. {
  1159. // Always add to the end. Always take from the beginning.
  1160. if(artifactsTransitionPos.empty())
  1161. return nullptr;
  1162. else
  1163. return &(*artifactsTransitionPos.begin());
  1164. }
  1165. if(vstd::contains(artifactsWorn, pos))
  1166. return &artifactsWorn.at(pos);
  1167. if(pos >= ArtifactPosition::AFTER_LAST )
  1168. {
  1169. int backpackPos = (int)pos - GameConstants::BACKPACK_START;
  1170. if(backpackPos < 0 || backpackPos >= artifactsInBackpack.size())
  1171. return nullptr;
  1172. else
  1173. return &artifactsInBackpack[backpackPos];
  1174. }
  1175. return nullptr;
  1176. }
  1177. bool CArtifactSet::isPositionFree(ArtifactPosition pos, bool onlyLockCheck) const
  1178. {
  1179. if(const ArtSlotInfo *s = getSlot(pos))
  1180. return (onlyLockCheck || !s->artifact) && !s->locked;
  1181. return true; //no slot means not used
  1182. }
  1183. ArtSlotInfo & CArtifactSet::retrieveNewArtSlot(ArtifactPosition slot)
  1184. {
  1185. assert(!vstd::contains(artifactsWorn, slot));
  1186. if(slot == ArtifactPosition::TRANSITION_POS)
  1187. {
  1188. // Always add to the end. Always take from the beginning.
  1189. artifactsTransitionPos.push_back(ArtSlotInfo());
  1190. return artifactsTransitionPos.back();
  1191. }
  1192. if(!ArtifactUtils::isSlotBackpack(slot))
  1193. return artifactsWorn[slot];
  1194. ArtSlotInfo newSlot;
  1195. size_t index = slot - GameConstants::BACKPACK_START;
  1196. auto position = artifactsInBackpack.begin() + index;
  1197. auto inserted = artifactsInBackpack.insert(position, newSlot);
  1198. return *inserted;
  1199. }
  1200. void CArtifactSet::setNewArtSlot(ArtifactPosition slot, CArtifactInstance *art, bool locked)
  1201. {
  1202. ArtSlotInfo & asi = retrieveNewArtSlot(slot);
  1203. asi.artifact = art;
  1204. asi.locked = locked;
  1205. }
  1206. void CArtifactSet::eraseArtSlot(ArtifactPosition slot)
  1207. {
  1208. if(slot == ArtifactPosition::TRANSITION_POS)
  1209. {
  1210. assert(!artifactsTransitionPos.empty());
  1211. artifactsTransitionPos.erase(artifactsTransitionPos.begin());
  1212. }
  1213. else if(ArtifactUtils::isSlotBackpack(slot))
  1214. {
  1215. auto backpackSlot = ArtifactPosition(slot - GameConstants::BACKPACK_START);
  1216. assert(artifactsInBackpack.begin() + backpackSlot < artifactsInBackpack.end());
  1217. artifactsInBackpack.erase(artifactsInBackpack.begin() + backpackSlot);
  1218. }
  1219. else
  1220. {
  1221. artifactsWorn.erase(slot);
  1222. }
  1223. }
  1224. void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
  1225. {
  1226. for(auto & elem : artifactsWorn)
  1227. if(elem.second.artifact && !elem.second.locked)
  1228. node->attachTo(*elem.second.artifact);
  1229. }
  1230. void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
  1231. {
  1232. //todo: creature and commander artifacts
  1233. if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
  1234. return;
  1235. if(!handler.saving)
  1236. {
  1237. assert(map);
  1238. artifactsInBackpack.clear();
  1239. artifactsWorn.clear();
  1240. }
  1241. auto s = handler.enterStruct(fieldName);
  1242. switch(bearerType())
  1243. {
  1244. case ArtBearer::HERO:
  1245. serializeJsonHero(handler, map);
  1246. break;
  1247. case ArtBearer::CREATURE:
  1248. serializeJsonCreature(handler, map);
  1249. break;
  1250. case ArtBearer::COMMANDER:
  1251. serializeJsonCommander(handler, map);
  1252. break;
  1253. default:
  1254. assert(false);
  1255. break;
  1256. }
  1257. }
  1258. void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
  1259. {
  1260. for(ArtifactPosition ap = ArtifactPosition::HEAD; ap < ArtifactPosition::AFTER_LAST; ap.advance(1))
  1261. {
  1262. serializeJsonSlot(handler, ap, map);
  1263. }
  1264. std::vector<ArtifactID> backpackTemp;
  1265. if(handler.saving)
  1266. {
  1267. backpackTemp.reserve(artifactsInBackpack.size());
  1268. for(const ArtSlotInfo & info : artifactsInBackpack)
  1269. backpackTemp.push_back(info.artifact->artType->getId());
  1270. }
  1271. handler.serializeIdArray(NArtifactPosition::backpack, backpackTemp);
  1272. if(!handler.saving)
  1273. {
  1274. for(const ArtifactID & artifactID : backpackTemp)
  1275. {
  1276. auto artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1277. auto slot = ArtifactPosition(GameConstants::BACKPACK_START + (si32)artifactsInBackpack.size());
  1278. if(artifact->canBePutAt(this, slot))
  1279. putArtifact(slot, artifact);
  1280. }
  1281. }
  1282. }
  1283. void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
  1284. {
  1285. logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
  1286. }
  1287. void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
  1288. {
  1289. logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
  1290. }
  1291. void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
  1292. {
  1293. ArtifactID artifactID;
  1294. if(handler.saving)
  1295. {
  1296. const ArtSlotInfo * info = getSlot(slot);
  1297. if(info != nullptr && !info->locked)
  1298. {
  1299. artifactID = info->artifact->artType->getId();
  1300. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1301. }
  1302. }
  1303. else
  1304. {
  1305. handler.serializeId(NArtifactPosition::namesHero[slot.num], artifactID, ArtifactID::NONE);
  1306. if(artifactID != ArtifactID::NONE)
  1307. {
  1308. auto artifact = CArtifactInstance::createArtifact(map, artifactID.toEnum());
  1309. if(artifact->canBePutAt(this, slot))
  1310. {
  1311. putArtifact(slot, artifact);
  1312. }
  1313. else
  1314. {
  1315. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  1316. }
  1317. }
  1318. }
  1319. }
  1320. CArtifactFittingSet::CArtifactFittingSet(ArtBearer::ArtBearer Bearer)
  1321. {
  1322. this->Bearer = Bearer;
  1323. }
  1324. void CArtifactFittingSet::setNewArtSlot(ArtifactPosition slot, CArtifactInstance * art, bool locked)
  1325. {
  1326. ArtSlotInfo & asi = retrieveNewArtSlot(slot);
  1327. asi.artifact = art;
  1328. asi.locked = locked;
  1329. }
  1330. void CArtifactFittingSet::putArtifact(ArtifactPosition pos, CArtifactInstance * art)
  1331. {
  1332. if(art && art->canBeDisassembled() && ArtifactUtils::isSlotEquipment(pos))
  1333. {
  1334. for(auto & part : dynamic_cast<CCombinedArtifactInstance*>(art)->constituentsInfo)
  1335. {
  1336. // For the ArtFittingSet is no needed to do figureMainConstituent, just lock slots
  1337. this->setNewArtSlot(part.art->firstAvailableSlot(this), part.art, true);
  1338. }
  1339. }
  1340. else
  1341. {
  1342. this->setNewArtSlot(pos, art, false);
  1343. }
  1344. }
  1345. ArtBearer::ArtBearer CArtifactFittingSet::bearerType() const
  1346. {
  1347. return this->Bearer;
  1348. }
  1349. DLL_LINKAGE ArtifactPosition ArtifactUtils::getArtifactDstPosition( const CArtifactInstance * artifact,
  1350. const CArtifactSet * target,
  1351. ArtBearer::ArtBearer bearer)
  1352. {
  1353. for(auto slot : artifact->artType->possibleSlots.at(bearer))
  1354. {
  1355. auto existingArtifact = target->getArt(slot);
  1356. auto existingArtInfo = target->getSlot(slot);
  1357. if(!existingArtifact
  1358. && (!existingArtInfo || !existingArtInfo->locked)
  1359. && artifact->canBePutAt(target, slot))
  1360. {
  1361. return slot;
  1362. }
  1363. }
  1364. return ArtifactPosition(GameConstants::BACKPACK_START);
  1365. }
  1366. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::unmovableSlots()
  1367. {
  1368. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1369. {
  1370. ArtifactPosition::SPELLBOOK,
  1371. ArtifactPosition::MACH4
  1372. };
  1373. return positions;
  1374. }
  1375. DLL_LINKAGE const std::vector<ArtifactPosition::EArtifactPosition> & ArtifactUtils::constituentWornSlots()
  1376. {
  1377. static const std::vector<ArtifactPosition::EArtifactPosition> positions =
  1378. {
  1379. ArtifactPosition::HEAD,
  1380. ArtifactPosition::SHOULDERS,
  1381. ArtifactPosition::NECK,
  1382. ArtifactPosition::RIGHT_HAND,
  1383. ArtifactPosition::LEFT_HAND,
  1384. ArtifactPosition::TORSO,
  1385. ArtifactPosition::RIGHT_RING,
  1386. ArtifactPosition::LEFT_RING,
  1387. ArtifactPosition::FEET,
  1388. ArtifactPosition::MISC1,
  1389. ArtifactPosition::MISC2,
  1390. ArtifactPosition::MISC3,
  1391. ArtifactPosition::MISC4,
  1392. ArtifactPosition::MISC5,
  1393. };
  1394. return positions;
  1395. }
  1396. DLL_LINKAGE bool ArtifactUtils::isArtRemovable(const std::pair<ArtifactPosition, ArtSlotInfo> & slot)
  1397. {
  1398. return slot.second.artifact
  1399. && !slot.second.locked
  1400. && !vstd::contains(unmovableSlots(), slot.first);
  1401. }
  1402. DLL_LINKAGE bool ArtifactUtils::checkSpellbookIsNeeded(const CGHeroInstance * heroPtr, ArtifactID artID, ArtifactPosition slot)
  1403. {
  1404. // TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  1405. // Titan's Thunder creates new spellbook on equip
  1406. if(artID == ArtifactID::TITANS_THUNDER && slot == ArtifactPosition::RIGHT_HAND)
  1407. {
  1408. if(heroPtr)
  1409. {
  1410. if(heroPtr && !heroPtr->hasSpellbook())
  1411. return true;
  1412. }
  1413. }
  1414. return false;
  1415. }
  1416. DLL_LINKAGE bool ArtifactUtils::isSlotBackpack(ArtifactPosition slot)
  1417. {
  1418. return slot >= GameConstants::BACKPACK_START;
  1419. }
  1420. DLL_LINKAGE bool ArtifactUtils::isSlotEquipment(ArtifactPosition slot)
  1421. {
  1422. return slot < GameConstants::BACKPACK_START && slot >= 0;
  1423. }
  1424. VCMI_LIB_NAMESPACE_END