CArtHandler.cpp 39 KB

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