CArtHandler.cpp 44 KB

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