CArtHandler.cpp 41 KB

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