CArtHandler.cpp 41 KB

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