CArtHandler.cpp 45 KB

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