CModHandler.cpp 43 KB

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