CModHandler.cpp 41 KB

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