CArtHandler.cpp 45 KB

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