CModHandler.cpp 27 KB

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