2
0

CModHandler.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. #include "StdInc.h"
  2. #include "CModHandler.h"
  3. #include "mapObjects/CObjectClassesHandler.h"
  4. #include "JsonNode.h"
  5. #include "filesystem/Filesystem.h"
  6. #include "filesystem/AdapterLoaders.h"
  7. #include "filesystem/CFilesystemLoader.h"
  8. #include "CCreatureHandler.h"
  9. #include "CArtHandler.h"
  10. #include "CTownHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "mapObjects/CObjectHandler.h"
  13. #include "StringConstants.h"
  14. #include "CStopWatch.h"
  15. #include "IHandlerBase.h"
  16. #include "spells/CSpellHandler.h"
  17. /*
  18. * CModHandler.cpp, part of VCMI engine
  19. *
  20. * Authors: listed in file AUTHORS in main folder
  21. *
  22. * License: GNU General Public License v2.0 or later
  23. * Full text of license available in license.txt file, in main folder
  24. *
  25. */
  26. CIdentifierStorage::CIdentifierStorage():
  27. state(LOADING)
  28. {
  29. }
  30. void CIdentifierStorage::checkIdentifier(std::string & ID)
  31. {
  32. if (boost::algorithm::ends_with(ID, "."))
  33. logGlobal->warnStream() << "BIG WARNING: identifier " << ID << " seems to be broken!";
  34. else
  35. {
  36. size_t pos = 0;
  37. do
  38. {
  39. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  40. {
  41. logGlobal->warnStream() << "Warning: identifier " << ID << " is not in camelCase!";
  42. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  43. }
  44. pos = ID.find('.', pos);
  45. }
  46. while(pos++ != std::string::npos);
  47. }
  48. }
  49. CIdentifierStorage::ObjectCallback::ObjectCallback(std::string localScope, std::string remoteScope, std::string type,
  50. std::string name, const std::function<void(si32)> & callback, bool optional):
  51. localScope(localScope),
  52. remoteScope(remoteScope),
  53. type(type),
  54. name(name),
  55. callback(callback),
  56. optional(optional)
  57. {}
  58. static std::pair<std::string, std::string> splitString(std::string input, char separator)
  59. {
  60. std::pair<std::string, std::string> ret;
  61. size_t splitPos = input.find(separator);
  62. if (splitPos == std::string::npos)
  63. {
  64. ret.first.clear();
  65. ret.second = input;
  66. }
  67. else
  68. {
  69. ret.first = input.substr(0, splitPos);
  70. ret.second = input.substr(splitPos + 1);
  71. }
  72. return ret;
  73. }
  74. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  75. {
  76. checkIdentifier(callback.type);
  77. checkIdentifier(callback.name);
  78. assert(!callback.localScope.empty());
  79. if (state != FINISHED) // enqueue request if loading is still in progress
  80. scheduledRequests.push_back(callback);
  81. else // execute immediately for "late" requests
  82. resolveIdentifier(callback);
  83. }
  84. void CIdentifierStorage::requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  85. {
  86. auto pair = splitString(name, ':'); // remoteScope:name
  87. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, false));
  88. }
  89. void CIdentifierStorage::requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)>& callback)
  90. {
  91. auto scopeAndFullName = splitString(fullName, ':');
  92. auto typeAndName = splitString(scopeAndFullName.second, '.');
  93. requestIdentifier(ObjectCallback(scope, scopeAndFullName.first, typeAndName.first, typeAndName.second, callback, false));
  94. }
  95. void CIdentifierStorage::requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  96. {
  97. auto pair = splitString(name.String(), ':'); // remoteScope:name
  98. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, false));
  99. }
  100. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  101. {
  102. auto pair = splitString(name.String(), ':'); // remoteScope:<type.name>
  103. auto pair2 = splitString(pair.second, '.'); // type.name
  104. requestIdentifier(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, callback, false));
  105. }
  106. void CIdentifierStorage::tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback)
  107. {
  108. auto pair = splitString(name, ':'); // remoteScope:name
  109. requestIdentifier(ObjectCallback(scope, pair.first, type, pair.second, callback, true));
  110. }
  111. void CIdentifierStorage::tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback)
  112. {
  113. auto pair = splitString(name.String(), ':'); // remoteScope:name
  114. requestIdentifier(ObjectCallback(name.meta, pair.first, type, pair.second, callback, true));
  115. }
  116. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string scope, std::string type, std::string name, bool silent)
  117. {
  118. auto pair = splitString(name, ':'); // remoteScope:name
  119. auto idList = getPossibleIdentifiers(ObjectCallback(scope, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  120. if (idList.size() == 1)
  121. return idList.front().id;
  122. if (!silent)
  123. logGlobal->errorStream() << "Failed to resolve identifier " << name << " of type " << type << " from mod " << scope;
  124. return boost::optional<si32>();
  125. }
  126. boost::optional<si32> CIdentifierStorage::getIdentifier(std::string type, const JsonNode & name, bool silent)
  127. {
  128. auto pair = splitString(name.String(), ':'); // remoteScope:name
  129. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, type, pair.second, std::function<void(si32)>(), silent));
  130. if (idList.size() == 1)
  131. return idList.front().id;
  132. if (!silent)
  133. logGlobal->errorStream() << "Failed to resolve identifier " << name.String() << " of type " << type << " from mod " << name.meta;
  134. return boost::optional<si32>();
  135. }
  136. boost::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  137. {
  138. auto pair = splitString(name.String(), ':'); // remoteScope:<type.name>
  139. auto pair2 = splitString(pair.second, '.'); // type.name
  140. auto idList = getPossibleIdentifiers(ObjectCallback(name.meta, pair.first, pair2.first, pair2.second, std::function<void(si32)>(), silent));
  141. if (idList.size() == 1)
  142. return idList.front().id;
  143. if (!silent)
  144. logGlobal->errorStream() << "Failed to resolve identifier " << name.String() << " of type " << pair2.first << " from mod " << name.meta;
  145. return boost::optional<si32>();
  146. }
  147. void CIdentifierStorage::registerObject(std::string scope, std::string type, std::string name, si32 identifier)
  148. {
  149. ObjectData data;
  150. data.scope = scope;
  151. data.id = identifier;
  152. std::string fullID = type + '.' + name;
  153. checkIdentifier(fullID);
  154. registeredObjects.insert(std::make_pair(fullID, data));
  155. }
  156. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  157. {
  158. std::set<std::string> allowedScopes;
  159. if (request.remoteScope.empty())
  160. {
  161. // normally ID's from all required mods, own mod and virtual "core" mod are allowed
  162. if (request.localScope != "core" && request.localScope != "")
  163. allowedScopes = VLC->modh->getModData(request.localScope).dependencies;
  164. allowedScopes.insert(request.localScope);
  165. allowedScopes.insert("core");
  166. }
  167. else
  168. {
  169. //...unless destination mod was specified explicitly
  170. auto myDeps = VLC->modh->getModData(request.localScope).dependencies;
  171. if (request.remoteScope == "core" || // allow only available to all core mod
  172. myDeps.count(request.remoteScope)) // or dependencies
  173. allowedScopes.insert(request.remoteScope);
  174. }
  175. std::string fullID = request.type + '.' + request.name;
  176. auto entries = registeredObjects.equal_range(fullID);
  177. if (entries.first != entries.second)
  178. {
  179. std::vector<ObjectData> locatedIDs;
  180. for (auto it = entries.first; it != entries.second; it++)
  181. {
  182. if (vstd::contains(allowedScopes, it->second.scope))
  183. {
  184. locatedIDs.push_back(it->second);
  185. }
  186. }
  187. return locatedIDs;
  188. }
  189. return std::vector<ObjectData>();
  190. }
  191. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  192. {
  193. auto identifiers = getPossibleIdentifiers(request);
  194. if (identifiers.size() == 1) // normally resolved ID
  195. {
  196. request.callback(identifiers.front().id);
  197. return true;
  198. }
  199. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  200. {
  201. return true;
  202. }
  203. // error found. Try to generate some debug info
  204. if (identifiers.size() == 0)
  205. logGlobal->errorStream() << "Unknown identifier!";
  206. else
  207. logGlobal->errorStream() << "Ambiguous identifier request!";
  208. logGlobal->errorStream() << "Request for " << request.type << "." << request.name << " from mod " << request.localScope;
  209. for (auto id : identifiers)
  210. {
  211. logGlobal->errorStream() << "\tID is available in mod " << id.scope;
  212. }
  213. return false;
  214. }
  215. void CIdentifierStorage::finalize()
  216. {
  217. state = FINALIZING;
  218. bool errorsFound = false;
  219. //Note: we may receive new requests during resolution phase -> end may change -> range for can't be used
  220. for(auto it = scheduledRequests.begin(); it != scheduledRequests.end(); it++)
  221. {
  222. errorsFound |= !resolveIdentifier(*it);
  223. }
  224. if (errorsFound)
  225. {
  226. for(auto object : registeredObjects)
  227. {
  228. logGlobal->traceStream() << object.second.scope << " : " << object.first << " -> " << object.second.id;
  229. }
  230. logGlobal->errorStream() << "All known identifiers were dumped into log file";
  231. }
  232. assert(errorsFound == false);
  233. state = FINISHED;
  234. }
  235. CContentHandler::ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, std::string objectName):
  236. handler(handler),
  237. objectName(objectName),
  238. originalData(handler->loadLegacyData(VLC->modh->settings.data["textData"][objectName].Float()))
  239. {
  240. for(auto & node : originalData)
  241. {
  242. node.setMeta("core");
  243. }
  244. }
  245. bool CContentHandler::ContentTypeHandler::preloadModData(std::string modName, std::vector<std::string> fileList, bool validate)
  246. {
  247. bool result;
  248. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  249. data.setMeta(modName);
  250. ModInfo & modInfo = modData[modName];
  251. for(auto entry : data.Struct())
  252. {
  253. size_t colon = entry.first.find(':');
  254. if (colon == std::string::npos)
  255. {
  256. // normal object, local to this mod
  257. modInfo.modData[entry.first].swap(entry.second);
  258. }
  259. else
  260. {
  261. std::string remoteName = entry.first.substr(0, colon);
  262. std::string objectName = entry.first.substr(colon + 1);
  263. // patching this mod? Send warning and continue - this situation can be handled normally
  264. if (remoteName == modName)
  265. logGlobal->warnStream() << "Redundant namespace definition for " << objectName;
  266. logGlobal->traceStream() << "Patching object " << objectName << " (" << remoteName << ") from " << modName;
  267. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  268. JsonUtils::merge(remoteConf, entry.second);
  269. }
  270. }
  271. return result;
  272. }
  273. bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool validate)
  274. {
  275. ModInfo & modInfo = modData[modName];
  276. bool result = true;
  277. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  278. handler->beforeValidate(data);
  279. if (validate)
  280. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  281. };
  282. // apply patches
  283. if (!modInfo.patches.isNull())
  284. JsonUtils::merge(modInfo.modData, modInfo.patches);
  285. for(auto & entry : modInfo.modData.Struct())
  286. {
  287. const std::string & name = entry.first;
  288. JsonNode & data = entry.second;
  289. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  290. {
  291. // try to add H3 object data
  292. size_t index = data["index"].Float();
  293. if (originalData.size() > index)
  294. {
  295. JsonUtils::merge(originalData[index], data);
  296. performValidate(originalData[index],name);
  297. handler->loadObject(modName, name, originalData[index], index);
  298. originalData[index].clear(); // do not use same data twice (same ID)
  299. continue;
  300. }
  301. }
  302. // normal new object or one with index bigger that data size
  303. performValidate(data,name);
  304. handler->loadObject(modName, name, data);
  305. }
  306. return result;
  307. }
  308. void CContentHandler::ContentTypeHandler::afterLoadFinalization()
  309. {
  310. handler->afterLoadFinalization();
  311. }
  312. CContentHandler::CContentHandler()
  313. {
  314. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  315. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  316. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  317. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  318. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  319. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  320. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  321. handlers.insert(std::make_pair("templates", ContentTypeHandler((IHandlerBase *)VLC->tplh, "template")));
  322. //TODO: any other types of moddables?
  323. }
  324. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  325. {
  326. bool result = true;
  327. for(auto & handler : handlers)
  328. {
  329. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  330. }
  331. return result;
  332. }
  333. bool CContentHandler::loadMod(std::string modName, bool validate)
  334. {
  335. bool result = true;
  336. for(auto & handler : handlers)
  337. {
  338. result &= handler.second.loadMod(modName, validate);
  339. }
  340. return result;
  341. }
  342. void CContentHandler::afterLoadFinalization()
  343. {
  344. for(auto & handler : handlers)
  345. {
  346. handler.second.afterLoadFinalization();
  347. }
  348. }
  349. void CContentHandler::preloadData(CModInfo & mod)
  350. {
  351. bool validate = (mod.validation != CModInfo::PASSED);
  352. // print message in format [<8-symbols checksum>] <modname>
  353. logGlobal->infoStream() << "\t\t[" << std::noshowbase << std::hex << std::setw(8) << std::setfill('0')
  354. << mod.checksum << "] " << mod.name;
  355. if (validate && mod.identifier != "core")
  356. {
  357. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  358. mod.validation = CModInfo::FAILED;
  359. }
  360. if (!preloadModData(mod.identifier, mod.config, validate))
  361. mod.validation = CModInfo::FAILED;
  362. }
  363. void CContentHandler::load(CModInfo & mod)
  364. {
  365. bool validate = (mod.validation != CModInfo::PASSED);
  366. if (!loadMod(mod.identifier, validate))
  367. mod.validation = CModInfo::FAILED;
  368. if (validate)
  369. {
  370. if (mod.validation != CModInfo::FAILED)
  371. logGlobal->infoStream() << "\t\t[DONE] " << mod.name;
  372. else
  373. logGlobal->errorStream() << "\t\t[FAIL] " << mod.name;
  374. }
  375. else
  376. logGlobal->infoStream() << "\t\t[SKIP] " << mod.name;
  377. }
  378. static JsonNode loadModSettings(std::string path)
  379. {
  380. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  381. {
  382. return JsonNode(ResourceID(path, EResType::TEXT));
  383. }
  384. // Probably new install. Create initial configuration
  385. CResourceHandler::get("local")->createResource(path);
  386. return JsonNode();
  387. }
  388. JsonNode addMeta(JsonNode config, std::string meta)
  389. {
  390. config.setMeta(meta);
  391. return config;
  392. }
  393. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  394. identifier(identifier),
  395. name(config["name"].String()),
  396. description(config["description"].String()),
  397. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  398. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  399. validation(PENDING),
  400. config(addMeta(config, identifier))
  401. {
  402. loadLocalData(local);
  403. }
  404. JsonNode CModInfo::saveLocalData() const
  405. {
  406. std::ostringstream stream;
  407. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  408. JsonNode conf;
  409. conf["active"].Bool() = enabled;
  410. conf["validated"].Bool() = validation != FAILED;
  411. conf["checksum"].String() = stream.str();
  412. return conf;
  413. }
  414. std::string CModInfo::getModDir(std::string name)
  415. {
  416. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  417. }
  418. std::string CModInfo::getModFile(std::string name)
  419. {
  420. return getModDir(name) + "/mod.json";
  421. }
  422. void CModInfo::updateChecksum(ui32 newChecksum)
  423. {
  424. // comment-out next line to force validation of all mods ignoring checksum
  425. if (newChecksum != checksum)
  426. {
  427. checksum = newChecksum;
  428. validation = PENDING;
  429. }
  430. }
  431. void CModInfo::loadLocalData(const JsonNode & data)
  432. {
  433. bool validated = false;
  434. enabled = true;
  435. checksum = 0;
  436. if (data.getType() == JsonNode::DATA_BOOL)
  437. {
  438. enabled = data.Bool();
  439. }
  440. if (data.getType() == JsonNode::DATA_STRUCT)
  441. {
  442. enabled = data["active"].Bool();
  443. validated = data["validated"].Bool();
  444. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  445. }
  446. if (enabled)
  447. validation = validated ? PASSED : PENDING;
  448. else
  449. validation = validated ? PASSED : FAILED;
  450. }
  451. CModHandler::CModHandler()
  452. {
  453. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  454. {
  455. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  456. }
  457. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  458. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  459. }
  460. void CModHandler::loadConfigFromFile (std::string name)
  461. {
  462. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  463. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  464. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Float();
  465. settings.MAX_HEROES_ON_MAP_PER_PLAYER = hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Float();
  466. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  467. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  468. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  469. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  470. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  471. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  472. const JsonNode & gameModules = settings.data["modules"];
  473. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  474. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  475. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  476. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  477. }
  478. // currentList is passed by value to get current list of depending mods
  479. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  480. {
  481. const CModInfo & mod = allMods.at(modID);
  482. // Mod already present? We found a loop
  483. if (vstd::contains(currentList, modID))
  484. {
  485. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  486. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  487. return true;
  488. }
  489. currentList.insert(modID);
  490. // recursively check every dependency of this mod
  491. for(const TModID & dependency : mod.dependencies)
  492. {
  493. if (hasCircularDependency(dependency, currentList))
  494. {
  495. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  496. return true;
  497. }
  498. }
  499. return false;
  500. }
  501. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  502. {
  503. for(const TModID & id : input)
  504. {
  505. const CModInfo & mod = allMods.at(id);
  506. for(const TModID & dep : mod.dependencies)
  507. {
  508. if (!vstd::contains(input, dep))
  509. {
  510. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  511. return false;
  512. }
  513. }
  514. for(const TModID & conflicting : mod.conflicts)
  515. {
  516. if (vstd::contains(input, conflicting))
  517. {
  518. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  519. return false;
  520. }
  521. }
  522. if (hasCircularDependency(id))
  523. return false;
  524. }
  525. return true;
  526. }
  527. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  528. {
  529. // Topological sort algorithm
  530. // May not be the fastest one but VCMI does not needs any speed here
  531. // Unless user have dozens of mods with complex dependencies this code should be fine
  532. // first - sort input to have input strictly based on name (and not on hashmap or anything else)
  533. boost::range::sort(input);
  534. std::vector <TModID> output;
  535. output.reserve(input.size());
  536. std::set <TModID> resolvedMods;
  537. // Check if all mod dependencies are resolved (moved to resolvedMods)
  538. auto isResolved = [&](const CModInfo mod) -> bool
  539. {
  540. for(const TModID & dependency : mod.dependencies)
  541. {
  542. if (!vstd::contains(resolvedMods, dependency))
  543. return false;
  544. }
  545. return true;
  546. };
  547. while (!input.empty())
  548. {
  549. std::set <TModID> toResolve; // list of mods resolved on this iteration
  550. for (auto it = input.begin(); it != input.end();)
  551. {
  552. if (isResolved(allMods.at(*it)))
  553. {
  554. toResolve.insert(*it);
  555. output.push_back(*it);
  556. it = input.erase(it);
  557. continue;
  558. }
  559. it++;
  560. }
  561. resolvedMods.insert(toResolve.begin(), toResolve.end());
  562. }
  563. return output;
  564. }
  565. std::vector<std::string> CModHandler::getModList(std::string path)
  566. {
  567. std::string modDir = boost::to_upper_copy(path + "MODS/");
  568. size_t depth = boost::range::count(modDir, '/');
  569. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  570. {
  571. if (id.getType() != EResType::DIRECTORY)
  572. return false;
  573. if (!boost::algorithm::starts_with(id.getName(), modDir))
  574. return false;
  575. if (boost::range::count(id.getName(), '/') != depth )
  576. return false;
  577. return true;
  578. });
  579. //storage for found mods
  580. std::vector<std::string> foundMods;
  581. for (auto & entry : list)
  582. {
  583. std::string name = entry.getName();
  584. name.erase(0, modDir.size()); //Remove path prefix
  585. // check if wog is actually present. Hack-ish but better than crash
  586. // TODO: remove soon (hopefully - before 0.96)
  587. if (name == "WOG")
  588. {
  589. if (!CResourceHandler::get("initial")->existsResource(ResourceID("DATA/ZVS", EResType::DIRECTORY)) &&
  590. !CResourceHandler::get("initial")->existsResource(ResourceID("MODS/WOG/DATA/ZVS", EResType::DIRECTORY)))
  591. {
  592. continue;
  593. }
  594. }
  595. if (!name.empty())
  596. foundMods.push_back(name);
  597. }
  598. return foundMods;
  599. }
  600. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  601. {
  602. for (std::string modName : getModList(path))
  603. {
  604. boost::to_lower(modName);
  605. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  606. if (CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  607. {
  608. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  609. if (!parent.empty()) // this is submod, add parent to dependecies
  610. mod.dependencies.insert(parent);
  611. allMods[modFullName] = mod;
  612. if (mod.enabled && enableMods)
  613. activeMods.push_back(modFullName);
  614. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  615. }
  616. }
  617. }
  618. void CModHandler::loadMods()
  619. {
  620. const JsonNode modConfig = loadModSettings("config/modSettings.json");
  621. loadMods("", "", modConfig["activeMods"], true);
  622. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  623. coreMod.name = "Original game files";
  624. }
  625. std::vector<std::string> CModHandler::getAllMods()
  626. {
  627. std::vector<std::string> modlist;
  628. for (auto & entry : allMods)
  629. modlist.push_back(entry.first);
  630. return modlist;
  631. }
  632. std::vector<std::string> CModHandler::getActiveMods()
  633. {
  634. return activeMods;
  635. }
  636. static JsonNode genDefaultFS()
  637. {
  638. // default FS config for mods: directory "Content" that acts as H3 root directory
  639. JsonNode defaultFS;
  640. defaultFS[""].Vector().resize(2);
  641. defaultFS[""].Vector()[0]["type"].String() = "zip";
  642. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  643. defaultFS[""].Vector()[1]["type"].String() = "dir";
  644. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  645. return defaultFS;
  646. }
  647. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  648. {
  649. static const JsonNode defaultFS = genDefaultFS();
  650. if (!conf["filesystem"].isNull())
  651. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  652. else
  653. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  654. }
  655. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  656. {
  657. boost::crc_32_type modChecksum;
  658. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  659. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  660. // second - add mod.json into checksum because filesystem does not contains this file
  661. // FIXME: remove workaround for core mod
  662. if (modName != "core")
  663. {
  664. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  665. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  666. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  667. }
  668. // third - add all detected text files from this mod into checksum
  669. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  670. {
  671. return resID.getType() == EResType::TEXT &&
  672. ( boost::starts_with(resID.getName(), "DATA") ||
  673. boost::starts_with(resID.getName(), "CONFIG"));
  674. });
  675. for (const ResourceID & file : files)
  676. {
  677. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  678. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  679. }
  680. return modChecksum.checksum();
  681. }
  682. void CModHandler::loadModFilesystems()
  683. {
  684. activeMods = resolveDependencies(activeMods);
  685. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::get("core")));
  686. for(std::string & modName : activeMods)
  687. {
  688. CModInfo & mod = allMods[modName];
  689. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  690. }
  691. }
  692. CModInfo & CModHandler::getModData(TModID modId)
  693. {
  694. CModInfo & mod = allMods.at(modId);
  695. assert(vstd::contains(activeMods, modId)); // not really necessary but won't hurt
  696. return mod;
  697. }
  698. void CModHandler::initializeConfig()
  699. {
  700. loadConfigFromFile("defaultMods.json");
  701. }
  702. void CModHandler::load()
  703. {
  704. CStopWatch totalTime, timer;
  705. CContentHandler content;
  706. logGlobal->infoStream() << "\tInitializing content handler: " << timer.getDiff() << " ms";
  707. for(const TModID & modName : activeMods)
  708. {
  709. logGlobal->traceStream() << "Generating checksum for " << modName;
  710. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  711. }
  712. // first - load virtual "core" mod that contains all data
  713. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  714. content.preloadData(coreMod);
  715. for(const TModID & modName : activeMods)
  716. content.preloadData(allMods[modName]);
  717. logGlobal->infoStream() << "\tParsing mod data: " << timer.getDiff() << " ms";
  718. content.load(coreMod);
  719. for(const TModID & modName : activeMods)
  720. content.load(allMods[modName]);
  721. logGlobal->infoStream() << "\tLoading mod data: " << timer.getDiff() << "ms";
  722. VLC->creh->loadCrExpBon();
  723. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  724. identifiers.finalize();
  725. logGlobal->infoStream() << "\tResolving identifiers: " << timer.getDiff() << " ms";
  726. content.afterLoadFinalization();
  727. logGlobal->infoStream() << "\tHandlers post-load finalization: " << timer.getDiff() << " ms";
  728. logGlobal->infoStream() << "\tAll game content loaded in " << totalTime.getDiff() << " ms";
  729. }
  730. void CModHandler::afterLoad()
  731. {
  732. JsonNode modSettings;
  733. for (auto & modEntry : allMods)
  734. {
  735. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  736. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  737. }
  738. modSettings["core"] = coreMod.saveLocalData();
  739. std::ofstream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  740. file << modSettings;
  741. }