CModHandler.cpp 40 KB

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