CModHandler.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. /*
  2. * CModHandler.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 "CModHandler.h"
  12. #include "mapObjects/CObjectClassesHandler.h"
  13. #include "filesystem/FileStream.h"
  14. #include "filesystem/AdapterLoaders.h"
  15. #include "filesystem/CFilesystemLoader.h"
  16. #include "CCreatureHandler.h"
  17. #include "CArtHandler.h"
  18. #include "CTownHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "mapObjects/CObjectHandler.h"
  21. #include "StringConstants.h"
  22. #include "CStopWatch.h"
  23. #include "IHandlerBase.h"
  24. #include "spells/CSpellHandler.h"
  25. #include "CSkillHandler.h"
  26. #include "ScriptHandler.h"
  27. #include <vstd/StringUtils.h>
  28. CIdentifierStorage::CIdentifierStorage():
  29. state(LOADING)
  30. {
  31. }
  32. CIdentifierStorage::~CIdentifierStorage()
  33. {
  34. }
  35. void CIdentifierStorage::checkIdentifier(std::string & ID)
  36. {
  37. if (boost::algorithm::ends_with(ID, "."))
  38. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  39. else
  40. {
  41. size_t pos = 0;
  42. do
  43. {
  44. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  45. {
  46. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  47. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  48. }
  49. pos = ID.find('.', pos);
  50. }
  51. while(pos++ != std::string::npos);
  52. }
  53. }
  54. CIdentifierStorage::ObjectCallback::ObjectCallback(
  55. std::string localScope, std::string remoteScope, std::string type,
  56. std::string name, const std::function<void(si32)> & callback,
  57. bool optional):
  58. localScope(localScope),
  59. remoteScope(remoteScope),
  60. type(type),
  61. name(name),
  62. callback(callback),
  63. optional(optional)
  64. {}
  65. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  66. {
  67. checkIdentifier(callback.type);
  68. checkIdentifier(callback.name);
  69. assert(!callback.localScope.empty());
  70. if (state != FINISHED) // enqueue request if loading is still in progress
  71. scheduledRequests.push_back(callback);
  72. else // execute immediately for "late" requests
  73. resolveIdentifier(callback);
  74. }
  75. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  76. {
  77. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  78. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  79. }
  80. void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)>& callback)
  81. {
  82. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  83. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  84. requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false));
  85. }
  86. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  87. {
  88. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  89. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  90. }
  91. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  92. {
  93. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  94. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  95. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  96. }
  97. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  98. {
  99. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  100. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  101. }
  102. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  103. {
  104. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  105. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  106. }
  107. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string type, std::string name, bool silent)
  108. {
  109. auto pair = vstd::splitStringToPair(name, ':'); // remoteScope:name
  110. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  111. if (idList.size() == 1)
  112. return idList.front().id;
  113. if (!silent)
  114. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  115. return boost::optional<si32>();
  116. }
  117. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  118. {
  119. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:name
  120. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  121. if (idList.size() == 1)
  122. return idList.front().id;
  123. if (!silent)
  124. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  125. return boost::optional<si32>();
  126. }
  127. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  128. {
  129. auto pair = vstd::splitStringToPair(name.String(), ':'); // remoteScope:<type.name>
  130. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  131. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  132. if (idList.size() == 1)
  133. return idList.front().id;
  134. if (!silent)
  135. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), pair2.first, name.meta);
  136. return boost::optional<si32>();
  137. }
  138. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string fullName, bool silent)
  139. {
  140. auto pair = vstd::splitStringToPair(fullName, ':'); // remoteScope:<type.name>
  141. auto pair2 = vstd::splitStringToPair(pair.second, '.'); // type.name
  142. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  143. if (idList.size() == 1)
  144. return idList.front().id;
  145. if (!silent)
  146. logMod->error("Failed to resolve identifier %s of type %s from mod %s", fullName, pair2.first, scope);
  147. return boost::optional<si32>();
  148. }
  149. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  150. {
  151. ObjectData data;
  152. data.scope = scope;
  153. data.id = identifier;
  154. std::string fullID = type + '.' + name;
  155. checkIdentifier(fullID);
  156. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  157. if(!vstd::containsMapping(registeredObjects, mapping))
  158. {
  159. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  160. registeredObjects.insert(mapping);
  161. }
  162. }
  163. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  164. {
  165. std::set<std::string> allowedScopes;
  166. if (request.remoteScope.empty())
  167. {
  168. // normally ID's from all required mods, own mod and virtual "core" mod are allowed
  169. if (request.localScope != "core" && request.localScope != "")
  170. allowedScopes = VLC->modh->getModData(request.localScope).dependencies;
  171. allowedScopes.insert(request.localScope);
  172. allowedScopes.insert("core");
  173. }
  174. else
  175. {
  176. //...unless destination mod was specified explicitly
  177. //note: getModData does not work for "core" by design
  178. //for map format support core mod has access to any mod
  179. //TODO: better solution for access from map?
  180. if(request.localScope == "core" || request.localScope == "")
  181. {
  182. allowedScopes.insert(request.remoteScope);
  183. }
  184. else
  185. {
  186. // allow only available to all core mod or dependencies
  187. auto myDeps = VLC->modh->getModData(request.localScope).dependencies;
  188. if(request.remoteScope == "core" || request.remoteScope == request.localScope || myDeps.count(request.remoteScope))
  189. allowedScopes.insert(request.remoteScope);
  190. }
  191. }
  192. std::string fullID = request.type + '.' + request.name;
  193. auto entries = registeredObjects.equal_range(fullID);
  194. if (entries.first != entries.second)
  195. {
  196. std::vector<ObjectData> locatedIDs;
  197. for (auto it = entries.first; it != entries.second; it++)
  198. {
  199. if (vstd::contains(allowedScopes, it->second.scope))
  200. {
  201. locatedIDs.push_back(it->second);
  202. }
  203. }
  204. return locatedIDs;
  205. }
  206. return std::vector<ObjectData>();
  207. }
  208. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  209. {
  210. auto identifiers = getPossibleIdentifiers(request);
  211. if (identifiers.size() == 1) // normally resolved ID
  212. {
  213. request.callback(identifiers.front().id);
  214. return true;
  215. }
  216. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  217. {
  218. return true;
  219. }
  220. // error found. Try to generate some debug info
  221. if (identifiers.size() == 0)
  222. logMod->error("Unknown identifier!");
  223. else
  224. logMod->error("Ambiguous identifier request!");
  225. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  226. for (auto id : identifiers)
  227. {
  228. logMod->error("\tID is available in mod %s", id.scope);
  229. }
  230. return false;
  231. }
  232. void CIdentifierStorage::finalize()
  233. {
  234. state = FINALIZING;
  235. bool errorsFound = false;
  236. //Note: we may receive new requests during resolution phase -> end may change -> range for can't be used
  237. for(auto it = scheduledRequests.begin(); it != scheduledRequests.end(); it++)
  238. {
  239. errorsFound |= !resolveIdentifier(*it);
  240. }
  241. if (errorsFound)
  242. {
  243. for(auto object : registeredObjects)
  244. {
  245. logMod->trace("%s : %s -> %d", object.second.scope, object.first, object.second.id);
  246. }
  247. logMod->error("All known identifiers were dumped into log file");
  248. }
  249. assert(errorsFound == false);
  250. state = FINISHED;
  251. }
  252. ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  253. handler(handler),
  254. objectName(objectName),
  255. originalData(handler->loadLegacyData((size_t)VLC->modh->settings.data["textData"][objectName].Float()))
  256. {
  257. for(auto & node : originalData)
  258. {
  259. node.setMeta("core");
  260. }
  261. }
  262. bool ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  263. {
  264. bool result;
  265. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  266. data.setMeta(modName);
  267. ModInfo & modInfo = modData[modName];
  268. for(auto entry : data.Struct())
  269. {
  270. size_t colon = entry.first.find(':');
  271. if (colon == std::string::npos)
  272. {
  273. // normal object, local to this mod
  274. modInfo.modData[entry.first].swap(entry.second);
  275. }
  276. else
  277. {
  278. std::string remoteName = entry.first.substr(0, colon);
  279. std::string objectName = entry.first.substr(colon + 1);
  280. // patching this mod? Send warning and continue - this situation can be handled normally
  281. if (remoteName == modName)
  282. logMod->warn("Redundant namespace definition for %s", objectName);
  283. logMod->trace("Patching object %s (%s) from %s", objectName, remoteName, modName);
  284. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  285. JsonUtils::merge(remoteConf, entry.second);
  286. }
  287. }
  288. return result;
  289. }
  290. bool ContentTypeHandler::loadMod(std::string modName, bool validate)
  291. {
  292. ModInfo & modInfo = modData[modName];
  293. bool result = true;
  294. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  295. handler->beforeValidate(data);
  296. if (validate)
  297. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  298. };
  299. // apply patches
  300. if (!modInfo.patches.isNull())
  301. JsonUtils::merge(modInfo.modData, modInfo.patches);
  302. for(auto & entry : modInfo.modData.Struct())
  303. {
  304. const std::string & name = entry.first;
  305. JsonNode & data = entry.second;
  306. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  307. {
  308. // try to add H3 object data
  309. size_t index = static_cast<size_t>(data["index"].Float());
  310. if(originalData.size() > index)
  311. {
  312. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  313. JsonUtils::merge(originalData[index], data);
  314. std::swap(originalData[index], data);
  315. originalData[index].clear(); // do not use same data twice (same ID)
  316. }
  317. else
  318. {
  319. logMod->warn("no original data in loadMod(%s) at index %d", name, index);
  320. }
  321. performValidate(data, name);
  322. handler->loadObject(modName, name, data, index);
  323. }
  324. else
  325. {
  326. // normal new object
  327. logMod->trace("no index in loadMod(%s)", name);
  328. performValidate(data,name);
  329. handler->loadObject(modName, name, data);
  330. }
  331. }
  332. return result;
  333. }
  334. void ContentTypeHandler::loadCustom()
  335. {
  336. handler->loadCustom();
  337. }
  338. void ContentTypeHandler::afterLoadFinalization()
  339. {
  340. handler->afterLoadFinalization();
  341. }
  342. CContentHandler::CContentHandler()
  343. {
  344. }
  345. void CContentHandler::init()
  346. {
  347. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  348. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  349. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  350. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  351. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  352. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  353. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  354. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  355. handlers.insert(std::make_pair("templates", ContentTypeHandler((IHandlerBase *)VLC->tplh, "template")));
  356. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  357. //TODO: any other types of moddables?
  358. }
  359. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  360. {
  361. bool result = true;
  362. for(auto & handler : handlers)
  363. {
  364. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  365. }
  366. return result;
  367. }
  368. bool CContentHandler::loadMod(std::string modName, bool validate)
  369. {
  370. bool result = true;
  371. for(auto & handler : handlers)
  372. {
  373. result &= handler.second.loadMod(modName, validate);
  374. }
  375. return result;
  376. }
  377. void CContentHandler::loadCustom()
  378. {
  379. for(auto & handler : handlers)
  380. {
  381. handler.second.loadCustom();
  382. }
  383. }
  384. void CContentHandler::afterLoadFinalization()
  385. {
  386. for(auto & handler : handlers)
  387. {
  388. handler.second.afterLoadFinalization();
  389. }
  390. }
  391. void CContentHandler::preloadData(CModInfo & mod)
  392. {
  393. bool validate = (mod.validation != CModInfo::PASSED);
  394. // print message in format [<8-symbols checksum>] <modname>
  395. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  396. if (validate && mod.identifier != "core")
  397. {
  398. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  399. mod.validation = CModInfo::FAILED;
  400. }
  401. if (!preloadModData(mod.identifier, mod.config, validate))
  402. mod.validation = CModInfo::FAILED;
  403. }
  404. void CContentHandler::load(CModInfo & mod)
  405. {
  406. bool validate = (mod.validation != CModInfo::PASSED);
  407. if (!loadMod(mod.identifier, validate))
  408. mod.validation = CModInfo::FAILED;
  409. if (validate)
  410. {
  411. if (mod.validation != CModInfo::FAILED)
  412. logMod->info("\t\t[DONE] %s", mod.name);
  413. else
  414. logMod->error("\t\t[FAIL] %s", mod.name);
  415. }
  416. else
  417. logMod->info("\t\t[SKIP] %s", mod.name);
  418. }
  419. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  420. {
  421. return handlers.at(name);
  422. }
  423. static JsonNode loadModSettings(std::string path)
  424. {
  425. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  426. {
  427. return JsonNode(ResourceID(path, EResType::TEXT));
  428. }
  429. // Probably new install. Create initial configuration
  430. CResourceHandler::get("local")->createResource(path);
  431. return JsonNode();
  432. }
  433. JsonNode addMeta(JsonNode config, std::string meta)
  434. {
  435. config.setMeta(meta);
  436. return config;
  437. }
  438. CModInfo::CModInfo():
  439. checksum(0),
  440. enabled(false),
  441. validation(PENDING)
  442. {
  443. }
  444. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  445. identifier(identifier),
  446. name(config["name"].String()),
  447. description(config["description"].String()),
  448. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  449. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  450. checksum(0),
  451. enabled(false),
  452. validation(PENDING),
  453. config(addMeta(config, identifier))
  454. {
  455. loadLocalData(local);
  456. }
  457. JsonNode CModInfo::saveLocalData() const
  458. {
  459. std::ostringstream stream;
  460. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  461. JsonNode conf;
  462. conf["active"].Bool() = enabled;
  463. conf["validated"].Bool() = validation != FAILED;
  464. conf["checksum"].String() = stream.str();
  465. return conf;
  466. }
  467. std::string CModInfo::getModDir(std::string name)
  468. {
  469. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  470. }
  471. std::string CModInfo::getModFile(std::string name)
  472. {
  473. return getModDir(name) + "/mod.json";
  474. }
  475. void CModInfo::updateChecksum(ui32 newChecksum)
  476. {
  477. // comment-out next line to force validation of all mods ignoring checksum
  478. if (newChecksum != checksum)
  479. {
  480. checksum = newChecksum;
  481. validation = PENDING;
  482. }
  483. }
  484. void CModInfo::loadLocalData(const JsonNode & data)
  485. {
  486. bool validated = false;
  487. enabled = true;
  488. checksum = 0;
  489. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  490. {
  491. enabled = data.Bool();
  492. }
  493. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  494. {
  495. enabled = data["active"].Bool();
  496. validated = data["validated"].Bool();
  497. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  498. }
  499. if (enabled)
  500. validation = validated ? PASSED : PENDING;
  501. else
  502. validation = validated ? PASSED : FAILED;
  503. }
  504. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  505. {
  506. modules.COMMANDERS = false;
  507. modules.STACK_ARTIFACT = false;
  508. modules.STACK_EXP = false;
  509. modules.MITHRIL = false;
  510. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  511. {
  512. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  513. }
  514. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  515. {
  516. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  517. identifiers.registerObject("core", "primarySkill", PrimarySkill::names[i], i);
  518. }
  519. }
  520. CModHandler::~CModHandler()
  521. {
  522. }
  523. void CModHandler::loadConfigFromFile (std::string name)
  524. {
  525. std::string paths;
  526. for(auto& p : CResourceHandler::get()->getResourceNames(ResourceID("config/" + name)))
  527. {
  528. paths += p.string() + ", ";
  529. }
  530. paths = paths.substr(0, paths.size() - 2);
  531. logMod->debug("Loading hardcoded features settings from [%s], result:", paths);
  532. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  533. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  534. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Integer());
  535. logMod->debug("\tMAX_HEROES_AVAILABLE_PER_PLAYER\t%d", settings.MAX_HEROES_AVAILABLE_PER_PLAYER);
  536. settings.MAX_HEROES_ON_MAP_PER_PLAYER = static_cast<int>(hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Integer());
  537. logMod->debug("\tMAX_HEROES_ON_MAP_PER_PLAYER\t%d", settings.MAX_HEROES_ON_MAP_PER_PLAYER);
  538. settings.CREEP_SIZE = static_cast<int>(hardcodedFeatures["CREEP_SIZE"].Integer());
  539. logMod->debug("\tCREEP_SIZE\t%d", settings.CREEP_SIZE);
  540. settings.WEEKLY_GROWTH = static_cast<int>(hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Integer());
  541. logMod->debug("\tWEEKLY_GROWTH\t%d", settings.WEEKLY_GROWTH);
  542. settings.NEUTRAL_STACK_EXP = static_cast<int>(hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Integer());
  543. logMod->debug("\tNEUTRAL_STACK_EXP\t%d", settings.NEUTRAL_STACK_EXP);
  544. settings.MAX_BUILDING_PER_TURN = static_cast<int>(hardcodedFeatures["MAX_BUILDING_PER_TURN"].Integer());
  545. logMod->debug("\tMAX_BUILDING_PER_TURN\t%d", settings.MAX_BUILDING_PER_TURN);
  546. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  547. logMod->debug("\tDWELLINGS_ACCUMULATE_CREATURES\t%d", static_cast<int>(settings.DWELLINGS_ACCUMULATE_CREATURES));
  548. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  549. logMod->debug("\tALL_CREATURES_GET_DOUBLE_MONTHS\t%d", static_cast<int>(settings.ALL_CREATURES_GET_DOUBLE_MONTHS));
  550. settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS = hardcodedFeatures["WINNING_HERO_WITH_NO_TROOPS_RETREATS"].Bool();
  551. logMod->debug("\tWINNING_HERO_WITH_NO_TROOPS_RETREATS\t%d", static_cast<int>(settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS));
  552. settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE = hardcodedFeatures["BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE"].Bool();
  553. logMod->debug("\tBLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE\t%d", static_cast<int>(settings.BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE));
  554. settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS = hardcodedFeatures["NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS"].Bool();
  555. logMod->debug("\tNO_RANDOM_SPECIAL_WEEKS_AND_MONTHS\t%d", static_cast<int>(settings.NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS));
  556. const JsonNode & gameModules = settings.data["modules"];
  557. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  558. logMod->debug("\tSTACK_EXP\t%d", static_cast<int>(modules.STACK_EXP));
  559. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  560. logMod->debug("\tSTACK_ARTIFACT\t%d", static_cast<int>(modules.STACK_ARTIFACT));
  561. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  562. logMod->debug("\tCOMMANDERS\t%d", static_cast<int>(modules.COMMANDERS));
  563. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  564. logMod->debug("\tMITHRIL\t%d", static_cast<int>(modules.MITHRIL));
  565. }
  566. // currentList is passed by value to get current list of depending mods
  567. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  568. {
  569. const CModInfo & mod = allMods.at(modID);
  570. // Mod already present? We found a loop
  571. if (vstd::contains(currentList, modID))
  572. {
  573. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  574. logMod->error("\t%s -> ", mod.name);
  575. return true;
  576. }
  577. currentList.insert(modID);
  578. // recursively check every dependency of this mod
  579. for(const TModID & dependency : mod.dependencies)
  580. {
  581. if (hasCircularDependency(dependency, currentList))
  582. {
  583. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  584. return true;
  585. }
  586. }
  587. return false;
  588. }
  589. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  590. {
  591. for(const TModID & id : input)
  592. {
  593. const CModInfo & mod = allMods.at(id);
  594. for(const TModID & dep : mod.dependencies)
  595. {
  596. if(!vstd::contains(input, dep))
  597. {
  598. logMod->error("Error: Mod %s requires missing %s!", mod.name, dep);
  599. return false;
  600. }
  601. }
  602. for(const TModID & conflicting : mod.conflicts)
  603. {
  604. if(vstd::contains(input, conflicting))
  605. {
  606. logMod->error("Error: Mod %s conflicts with %s!", mod.name, allMods.at(conflicting).name);
  607. return false;
  608. }
  609. }
  610. if(hasCircularDependency(id))
  611. return false;
  612. }
  613. return true;
  614. }
  615. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  616. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  617. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  618. {
  619. // Topological sort algorithm.
  620. // TODO: Investigate possible ways to improve performance.
  621. boost::range::sort(modsToResolve); // Sort mods per name
  622. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  623. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  624. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  625. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  626. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  627. {
  628. if(mod.dependencies.size() > resolvedModIDs.size())
  629. return CModInfo::PENDING;
  630. for(const TModID & dependency : mod.dependencies)
  631. {
  632. if(!vstd::contains(resolvedModIDs, dependency))
  633. return CModInfo::PENDING;
  634. }
  635. return CModInfo::PASSED;
  636. };
  637. while(true)
  638. {
  639. std::set <TModID> resolvedOnCurrentTreeLevel;
  640. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  641. {
  642. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  643. {
  644. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  645. sortedValidMods.push_back(*it);
  646. it = modsToResolve.erase(it);
  647. continue;
  648. }
  649. it++;
  650. }
  651. if(resolvedOnCurrentTreeLevel.size())
  652. {
  653. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  654. continue;
  655. }
  656. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  657. break;
  658. }
  659. // Left mods have unresolved dependencies, output all to log.
  660. for(const auto & brokenModID : modsToResolve)
  661. {
  662. const CModInfo & brokenMod = allMods.at(brokenModID);
  663. for(const TModID & dependency : brokenMod.dependencies)
  664. {
  665. if(!vstd::contains(resolvedModIDs, dependency))
  666. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  667. }
  668. }
  669. return sortedValidMods;
  670. }
  671. std::vector<std::string> CModHandler::getModList(std::string path)
  672. {
  673. std::string modDir = boost::to_upper_copy(path + "MODS/");
  674. size_t depth = boost::range::count(modDir, '/');
  675. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  676. {
  677. if (id.getType() != EResType::DIRECTORY)
  678. return false;
  679. if (!boost::algorithm::starts_with(id.getName(), modDir))
  680. return false;
  681. if (boost::range::count(id.getName(), '/') != depth )
  682. return false;
  683. return true;
  684. });
  685. //storage for found mods
  686. std::vector<std::string> foundMods;
  687. for (auto & entry : list)
  688. {
  689. std::string name = entry.getName();
  690. name.erase(0, modDir.size()); //Remove path prefix
  691. if (!name.empty())
  692. foundMods.push_back(name);
  693. }
  694. return foundMods;
  695. }
  696. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  697. {
  698. for(std::string modName : getModList(path))
  699. loadOneMod(modName, parent, modSettings, enableMods);
  700. }
  701. void CModHandler::loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods)
  702. {
  703. boost::to_lower(modName);
  704. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  705. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  706. {
  707. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  708. if (!parent.empty()) // this is submod, add parent to dependencies
  709. mod.dependencies.insert(parent);
  710. allMods[modFullName] = mod;
  711. if (mod.enabled && enableMods)
  712. activeMods.push_back(modFullName);
  713. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  714. }
  715. }
  716. void CModHandler::loadMods(bool onlyEssential)
  717. {
  718. JsonNode modConfig;
  719. if(onlyEssential)
  720. {
  721. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  722. }
  723. else
  724. {
  725. modConfig = loadModSettings("config/modSettings.json");
  726. loadMods("", "", modConfig["activeMods"], true);
  727. }
  728. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  729. coreMod.name = "Original game files";
  730. }
  731. std::vector<std::string> CModHandler::getAllMods()
  732. {
  733. std::vector<std::string> modlist;
  734. for (auto & entry : allMods)
  735. modlist.push_back(entry.first);
  736. return modlist;
  737. }
  738. std::vector<std::string> CModHandler::getActiveMods()
  739. {
  740. return activeMods;
  741. }
  742. static JsonNode genDefaultFS()
  743. {
  744. // default FS config for mods: directory "Content" that acts as H3 root directory
  745. JsonNode defaultFS;
  746. defaultFS[""].Vector().resize(2);
  747. defaultFS[""].Vector()[0]["type"].String() = "zip";
  748. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  749. defaultFS[""].Vector()[1]["type"].String() = "dir";
  750. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  751. return defaultFS;
  752. }
  753. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  754. {
  755. static const JsonNode defaultFS = genDefaultFS();
  756. if (!conf["filesystem"].isNull())
  757. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  758. else
  759. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  760. }
  761. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  762. {
  763. boost::crc_32_type modChecksum;
  764. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  765. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  766. // second - add mod.json into checksum because filesystem does not contains this file
  767. // FIXME: remove workaround for core mod
  768. if (modName != "core")
  769. {
  770. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  771. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  772. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  773. }
  774. // third - add all detected text files from this mod into checksum
  775. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  776. {
  777. return resID.getType() == EResType::TEXT &&
  778. ( boost::starts_with(resID.getName(), "DATA") ||
  779. boost::starts_with(resID.getName(), "CONFIG"));
  780. });
  781. for (const ResourceID & file : files)
  782. {
  783. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  784. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  785. }
  786. return modChecksum.checksum();
  787. }
  788. void CModHandler::loadModFilesystems()
  789. {
  790. activeMods = validateAndSortDependencies(activeMods);
  791. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::get("core")));
  792. for(std::string & modName : activeMods)
  793. {
  794. CModInfo & mod = allMods[modName];
  795. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  796. }
  797. }
  798. CModInfo & CModHandler::getModData(TModID modId)
  799. {
  800. auto it = allMods.find(modId);
  801. if(it == allMods.end())
  802. {
  803. throw std::runtime_error("Mod not found '" + modId+"'");
  804. }
  805. else
  806. {
  807. return it->second;
  808. }
  809. }
  810. void CModHandler::initializeConfig()
  811. {
  812. loadConfigFromFile("defaultMods.json");
  813. }
  814. void CModHandler::load()
  815. {
  816. CStopWatch totalTime, timer;
  817. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  818. content->init();
  819. for(const TModID & modName : activeMods)
  820. {
  821. logMod->trace("Generating checksum for %s", modName);
  822. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  823. }
  824. // first - load virtual "core" mod that contains all data
  825. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  826. content->preloadData(coreMod);
  827. for(const TModID & modName : activeMods)
  828. content->preloadData(allMods[modName]);
  829. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  830. content->load(coreMod);
  831. for(const TModID & modName : activeMods)
  832. content->load(allMods[modName]);
  833. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  834. content->loadCustom();
  835. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  836. VLC->creh->loadCrExpBon();
  837. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  838. identifiers.finalize();
  839. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  840. content->afterLoadFinalization();
  841. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  842. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  843. }
  844. void CModHandler::afterLoad(bool onlyEssential)
  845. {
  846. JsonNode modSettings;
  847. for (auto & modEntry : allMods)
  848. {
  849. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  850. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  851. }
  852. modSettings["core"] = coreMod.saveLocalData();
  853. if(!onlyEssential)
  854. {
  855. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  856. file << modSettings.toJson();
  857. }
  858. }
  859. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  860. {
  861. auto p = vstd::splitStringToPair(identifier, ':');
  862. if(p.first.empty())
  863. p.first = scope;
  864. if(p.first == remoteScope)
  865. p.first.clear();
  866. return p.first.empty() ? p.second : p.first + ":" + p.second;
  867. }
  868. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  869. {
  870. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  871. scope = p.first;
  872. auto p2 = vstd::splitStringToPair(p.second, '.');
  873. if(p2.first != "")
  874. {
  875. type = p2.first;
  876. identifier = p2.second;
  877. }
  878. else
  879. {
  880. type = p.second;
  881. identifier = "";
  882. }
  883. }
  884. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  885. {
  886. if(type == "")
  887. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  888. std::string actualScope = scope;
  889. std::string actualName = identifier;
  890. //ignore scope if identifier is scoped
  891. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  892. if(scopeAndName.first != "")
  893. {
  894. actualScope = scopeAndName.first;
  895. actualName = scopeAndName.second;
  896. }
  897. if(actualScope == "")
  898. {
  899. return actualName == "" ? type : type + "." + actualName;
  900. }
  901. else
  902. {
  903. return actualName == "" ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  904. }
  905. }