CModHandler.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. const JsonNode & baseBonuses = VLC->modh->settings.data["heroBaseBonuses"];
  697. logMod->debug("\tLoading base hero bonuses");
  698. for(const auto & b : baseBonuses.Vector())
  699. heroBaseBonuses.emplace_back(JsonUtils::parseBonus(b));
  700. }
  701. // currentList is passed by value to get current list of depending mods
  702. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  703. {
  704. const CModInfo & mod = allMods.at(modID);
  705. // Mod already present? We found a loop
  706. if (vstd::contains(currentList, modID))
  707. {
  708. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  709. logMod->error("\t%s -> ", mod.name);
  710. return true;
  711. }
  712. currentList.insert(modID);
  713. // recursively check every dependency of this mod
  714. for(const TModID & dependency : mod.dependencies)
  715. {
  716. if (hasCircularDependency(dependency, currentList))
  717. {
  718. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  719. return true;
  720. }
  721. }
  722. return false;
  723. }
  724. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  725. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  726. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  727. {
  728. // Topological sort algorithm.
  729. // TODO: Investigate possible ways to improve performance.
  730. boost::range::sort(modsToResolve); // Sort mods per name
  731. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  732. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  733. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  734. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  735. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  736. {
  737. if(mod.dependencies.size() > resolvedModIDs.size())
  738. return CModInfo::PENDING;
  739. for(const TModID & dependency : mod.dependencies)
  740. {
  741. if(!vstd::contains(resolvedModIDs, dependency))
  742. return CModInfo::PENDING;
  743. }
  744. return CModInfo::PASSED;
  745. };
  746. while(true)
  747. {
  748. std::set <TModID> resolvedOnCurrentTreeLevel;
  749. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  750. {
  751. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  752. {
  753. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  754. sortedValidMods.push_back(*it);
  755. it = modsToResolve.erase(it);
  756. continue;
  757. }
  758. it++;
  759. }
  760. if(resolvedOnCurrentTreeLevel.size())
  761. {
  762. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  763. continue;
  764. }
  765. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  766. break;
  767. }
  768. // Left mods have unresolved dependencies, output all to log.
  769. for(const auto & brokenModID : modsToResolve)
  770. {
  771. const CModInfo & brokenMod = allMods.at(brokenModID);
  772. for(const TModID & dependency : brokenMod.dependencies)
  773. {
  774. if(!vstd::contains(resolvedModIDs, dependency))
  775. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  776. }
  777. }
  778. return sortedValidMods;
  779. }
  780. std::vector<std::string> CModHandler::getModList(std::string path)
  781. {
  782. std::string modDir = boost::to_upper_copy(path + "MODS/");
  783. size_t depth = boost::range::count(modDir, '/');
  784. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  785. {
  786. if (id.getType() != EResType::DIRECTORY)
  787. return false;
  788. if (!boost::algorithm::starts_with(id.getName(), modDir))
  789. return false;
  790. if (boost::range::count(id.getName(), '/') != depth )
  791. return false;
  792. return true;
  793. });
  794. //storage for found mods
  795. std::vector<std::string> foundMods;
  796. for (auto & entry : list)
  797. {
  798. std::string name = entry.getName();
  799. name.erase(0, modDir.size()); //Remove path prefix
  800. if (!name.empty())
  801. foundMods.push_back(name);
  802. }
  803. return foundMods;
  804. }
  805. bool CModHandler::isScopeReserved(const TModID & scope)
  806. {
  807. //following scopes are reserved - either in use by mod system or by filesystem
  808. static const std::array<TModID, 9> reservedScopes = {
  809. "core", "map", "game", "root", "saves", "config", "local", "initial", "mapEditor"
  810. };
  811. return std::find(reservedScopes.begin(), reservedScopes.end(), scope) != reservedScopes.end();
  812. }
  813. const TModID & CModHandler::scopeBuiltin()
  814. {
  815. static const TModID scope = "core";
  816. return scope;
  817. }
  818. const TModID & CModHandler::scopeGame()
  819. {
  820. static const TModID scope = "game";
  821. return scope;
  822. }
  823. const TModID & CModHandler::scopeMap()
  824. {
  825. //TODO: implement accessing map dependencies for both H3 and VCMI maps
  826. // for now, allow access to any identifiers
  827. static const TModID scope = "game";
  828. return scope;
  829. }
  830. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  831. {
  832. for(std::string modName : getModList(path))
  833. loadOneMod(modName, parent, modSettings, enableMods);
  834. }
  835. void CModHandler::loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods)
  836. {
  837. boost::to_lower(modName);
  838. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  839. if ( isScopeReserved(modFullName))
  840. {
  841. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  842. return;
  843. }
  844. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  845. {
  846. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  847. if (!parent.empty()) // this is submod, add parent to dependencies
  848. mod.dependencies.insert(parent);
  849. allMods[modFullName] = mod;
  850. if (mod.isEnabled() && enableMods)
  851. activeMods.push_back(modFullName);
  852. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  853. }
  854. }
  855. void CModHandler::loadMods(bool onlyEssential)
  856. {
  857. JsonNode modConfig;
  858. if(onlyEssential)
  859. {
  860. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  861. }
  862. else
  863. {
  864. modConfig = loadModSettings("config/modSettings.json");
  865. loadMods("", "", modConfig["activeMods"], true);
  866. }
  867. coreMod = CModInfo(CModHandler::scopeBuiltin(), modConfig[CModHandler::scopeBuiltin()], JsonNode(ResourceID("config/gameConfig.json")));
  868. coreMod.name = "Original game files";
  869. }
  870. std::vector<std::string> CModHandler::getAllMods()
  871. {
  872. std::vector<std::string> modlist;
  873. for (auto & entry : allMods)
  874. modlist.push_back(entry.first);
  875. return modlist;
  876. }
  877. std::vector<std::string> CModHandler::getActiveMods()
  878. {
  879. return activeMods;
  880. }
  881. static JsonNode genDefaultFS()
  882. {
  883. // default FS config for mods: directory "Content" that acts as H3 root directory
  884. JsonNode defaultFS;
  885. defaultFS[""].Vector().resize(2);
  886. defaultFS[""].Vector()[0]["type"].String() = "zip";
  887. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  888. defaultFS[""].Vector()[1]["type"].String() = "dir";
  889. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  890. return defaultFS;
  891. }
  892. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  893. {
  894. static const JsonNode defaultFS = genDefaultFS();
  895. if (!conf["filesystem"].isNull())
  896. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  897. else
  898. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  899. }
  900. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  901. {
  902. boost::crc_32_type modChecksum;
  903. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  904. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  905. // second - add mod.json into checksum because filesystem does not contains this file
  906. // FIXME: remove workaround for core mod
  907. if (modName != CModHandler::scopeBuiltin())
  908. {
  909. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  910. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  911. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  912. }
  913. // third - add all detected text files from this mod into checksum
  914. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  915. {
  916. return resID.getType() == EResType::TEXT &&
  917. ( boost::starts_with(resID.getName(), "DATA") ||
  918. boost::starts_with(resID.getName(), "CONFIG"));
  919. });
  920. for (const ResourceID & file : files)
  921. {
  922. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  923. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  924. }
  925. return modChecksum.checksum();
  926. }
  927. void CModHandler::loadModFilesystems()
  928. {
  929. CGeneralTextHandler::detectInstallParameters();
  930. activeMods = validateAndSortDependencies(activeMods);
  931. coreMod.updateChecksum(calculateModChecksum(CModHandler::scopeBuiltin(), CResourceHandler::get(CModHandler::scopeBuiltin())));
  932. for(std::string & modName : activeMods)
  933. {
  934. CModInfo & mod = allMods[modName];
  935. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  936. }
  937. }
  938. TModID CModHandler::findResourceOrigin(const ResourceID & name)
  939. {
  940. for(const auto & modID : boost::adaptors::reverse(activeMods))
  941. {
  942. if(CResourceHandler::get(modID)->existsResource(name))
  943. return modID;
  944. }
  945. if(CResourceHandler::get("core")->existsResource(name))
  946. return "core";
  947. if(CResourceHandler::get("mapEditor")->existsResource(name))
  948. return "core"; // Workaround for loading maps via map editor
  949. assert(0);
  950. return "";
  951. }
  952. std::string CModHandler::getModLanguage(const TModID& modId) const
  953. {
  954. if ( modId == "core")
  955. return VLC->generaltexth->getInstalledLanguage();
  956. return allMods.at(modId).baseLanguage;
  957. }
  958. std::set<TModID> CModHandler::getModDependencies(TModID modId, bool & isModFound) const
  959. {
  960. auto it = allMods.find(modId);
  961. isModFound = (it != allMods.end());
  962. if(isModFound)
  963. return it->second.dependencies;
  964. logMod->error("Mod not found: '%s'", modId);
  965. return {};
  966. }
  967. void CModHandler::initializeConfig()
  968. {
  969. loadConfigFromFile("defaultMods.json");
  970. }
  971. bool CModHandler::validateTranslations(TModID modName) const
  972. {
  973. bool result = true;
  974. const auto & mod = allMods.at(modName);
  975. {
  976. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  977. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  978. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  979. }
  980. for(const auto & language : Languages::getLanguageList())
  981. {
  982. if (!language.hasTranslation)
  983. continue;
  984. if (mod.config[language.identifier].isNull())
  985. continue;
  986. if (mod.config[language.identifier]["skipValidation"].Bool())
  987. continue;
  988. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  989. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  990. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  991. }
  992. return result;
  993. }
  994. void CModHandler::loadTranslation(TModID modName)
  995. {
  996. const auto & mod = allMods[modName];
  997. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  998. std::string modBaseLanguage = allMods[modName].baseLanguage;
  999. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  1000. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  1001. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  1002. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  1003. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  1004. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  1005. }
  1006. void CModHandler::load()
  1007. {
  1008. CStopWatch totalTime;
  1009. CStopWatch timer;
  1010. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  1011. content->init();
  1012. for(const TModID & modName : activeMods)
  1013. {
  1014. logMod->trace("Generating checksum for %s", modName);
  1015. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  1016. }
  1017. // first - load virtual builtin mod that contains all data
  1018. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  1019. content->preloadData(coreMod);
  1020. for(const TModID & modName : activeMods)
  1021. content->preloadData(allMods[modName]);
  1022. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  1023. content->load(coreMod);
  1024. for(const TModID & modName : activeMods)
  1025. content->load(allMods[modName]);
  1026. #if SCRIPTING_ENABLED
  1027. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  1028. #endif
  1029. content->loadCustom();
  1030. for(const TModID & modName : activeMods)
  1031. loadTranslation(modName);
  1032. for(const TModID & modName : activeMods)
  1033. if (!validateTranslations(modName))
  1034. allMods[modName].validation = CModInfo::FAILED;
  1035. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  1036. VLC->creh->loadCrExpBon();
  1037. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  1038. identifiers.finalize();
  1039. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  1040. content->afterLoadFinalization();
  1041. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  1042. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  1043. }
  1044. void CModHandler::afterLoad(bool onlyEssential)
  1045. {
  1046. JsonNode modSettings;
  1047. for (auto & modEntry : allMods)
  1048. {
  1049. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  1050. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  1051. }
  1052. modSettings[CModHandler::scopeBuiltin()] = coreMod.saveLocalData();
  1053. if(!onlyEssential)
  1054. {
  1055. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  1056. file << modSettings.toJson();
  1057. }
  1058. }
  1059. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  1060. {
  1061. auto p = vstd::splitStringToPair(identifier, ':');
  1062. if(p.first.empty())
  1063. p.first = scope;
  1064. if(p.first == remoteScope)
  1065. p.first.clear();
  1066. return p.first.empty() ? p.second : p.first + ":" + p.second;
  1067. }
  1068. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  1069. {
  1070. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  1071. scope = p.first;
  1072. auto p2 = vstd::splitStringToPair(p.second, '.');
  1073. if(p2.first != "")
  1074. {
  1075. type = p2.first;
  1076. identifier = p2.second;
  1077. }
  1078. else
  1079. {
  1080. type = p.second;
  1081. identifier.clear();
  1082. }
  1083. }
  1084. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  1085. {
  1086. if(type.empty())
  1087. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  1088. std::string actualScope = scope;
  1089. std::string actualName = identifier;
  1090. //ignore scope if identifier is scoped
  1091. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  1092. if(scopeAndName.first != "")
  1093. {
  1094. actualScope = scopeAndName.first;
  1095. actualName = scopeAndName.second;
  1096. }
  1097. if(actualScope.empty())
  1098. {
  1099. return actualName.empty() ? type : type + "." + actualName;
  1100. }
  1101. else
  1102. {
  1103. return actualName.empty() ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  1104. }
  1105. }
  1106. VCMI_LIB_NAMESPACE_END