2
0

CModHandler.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. logGlobal->traceStream() << "Patching object " << objectName << " (" << remoteName << ") from " << modName;
  261. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  262. JsonUtils::merge(remoteConf, entry.second);
  263. }
  264. }
  265. return result;
  266. }
  267. bool CContentHandler::ContentTypeHandler::loadMod(std::string modName, bool validate)
  268. {
  269. ModInfo & modInfo = modData[modName];
  270. bool result = true;
  271. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  272. handler->beforeValidate(data);
  273. if (validate)
  274. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  275. };
  276. // apply patches
  277. if (!modInfo.patches.isNull())
  278. JsonUtils::merge(modInfo.modData, modInfo.patches);
  279. for(auto & entry : modInfo.modData.Struct())
  280. {
  281. const std::string & name = entry.first;
  282. JsonNode & data = entry.second;
  283. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  284. {
  285. // try to add H3 object data
  286. size_t index = data["index"].Float();
  287. if (originalData.size() > index)
  288. {
  289. JsonUtils::merge(originalData[index], data);
  290. performValidate(originalData[index],name);
  291. handler->loadObject(modName, name, originalData[index], index);
  292. originalData[index].clear(); // do not use same data twice (same ID)
  293. continue;
  294. }
  295. }
  296. // normal new object or one with index bigger that data size
  297. performValidate(data,name);
  298. handler->loadObject(modName, name, data);
  299. }
  300. return result;
  301. }
  302. void CContentHandler::ContentTypeHandler::afterLoadFinalization()
  303. {
  304. handler->afterLoadFinalization();
  305. }
  306. CContentHandler::CContentHandler()
  307. {
  308. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  309. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  310. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  311. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  312. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  313. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  314. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  315. //TODO: any other types of moddables?
  316. }
  317. bool CContentHandler::preloadModData(std::string modName, JsonNode modConfig, bool validate)
  318. {
  319. bool result = true;
  320. for(auto & handler : handlers)
  321. {
  322. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  323. }
  324. return result;
  325. }
  326. bool CContentHandler::loadMod(std::string modName, bool validate)
  327. {
  328. bool result = true;
  329. for(auto & handler : handlers)
  330. {
  331. result &= handler.second.loadMod(modName, validate);
  332. }
  333. return result;
  334. }
  335. void CContentHandler::afterLoadFinalization()
  336. {
  337. for(auto & handler : handlers)
  338. {
  339. handler.second.afterLoadFinalization();
  340. }
  341. }
  342. void CContentHandler::preloadData(CModInfo & mod)
  343. {
  344. bool validate = (mod.validation != CModInfo::PASSED);
  345. // print message in format [<8-symbols checksum>] <modname>
  346. logGlobal->infoStream() << "\t\t[" << std::noshowbase << std::hex << std::setw(8) << std::setfill('0')
  347. << mod.checksum << "] " << mod.name;
  348. if (validate && mod.identifier != "core")
  349. {
  350. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  351. mod.validation = CModInfo::FAILED;
  352. }
  353. if (!preloadModData(mod.identifier, mod.config, validate))
  354. mod.validation = CModInfo::FAILED;
  355. }
  356. void CContentHandler::load(CModInfo & mod)
  357. {
  358. bool validate = (mod.validation != CModInfo::PASSED);
  359. if (!loadMod(mod.identifier, validate))
  360. mod.validation = CModInfo::FAILED;
  361. if (validate)
  362. {
  363. if (mod.validation != CModInfo::FAILED)
  364. logGlobal->infoStream() << "\t\t[DONE] " << mod.name;
  365. else
  366. logGlobal->errorStream() << "\t\t[FAIL] " << mod.name;
  367. }
  368. else
  369. logGlobal->infoStream() << "\t\t[SKIP] " << mod.name;
  370. }
  371. static JsonNode loadModSettings(std::string path)
  372. {
  373. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  374. {
  375. return JsonNode(ResourceID(path, EResType::TEXT));
  376. }
  377. // Probably new install. Create initial configuration
  378. CResourceHandler::get("local")->createResource(path);
  379. return JsonNode();
  380. }
  381. JsonNode addMeta(JsonNode config, std::string meta)
  382. {
  383. config.setMeta(meta);
  384. return std::move(config);
  385. }
  386. CModInfo::CModInfo(std::string identifier,const JsonNode & local, const JsonNode & config):
  387. identifier(identifier),
  388. name(config["name"].String()),
  389. description(config["description"].String()),
  390. dependencies(config["depends"].convertTo<std::set<std::string> >()),
  391. conflicts(config["conflicts"].convertTo<std::set<std::string> >()),
  392. validation(PENDING),
  393. config(addMeta(config, identifier))
  394. {
  395. loadLocalData(local);
  396. }
  397. JsonNode CModInfo::saveLocalData() const
  398. {
  399. std::ostringstream stream;
  400. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  401. JsonNode conf;
  402. conf["active"].Bool() = enabled;
  403. conf["validated"].Bool() = validation != FAILED;
  404. conf["checksum"].String() = stream.str();
  405. return conf;
  406. }
  407. std::string CModInfo::getModDir(std::string name)
  408. {
  409. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  410. }
  411. std::string CModInfo::getModFile(std::string name)
  412. {
  413. return getModDir(name) + "/mod.json";
  414. }
  415. void CModInfo::updateChecksum(ui32 newChecksum)
  416. {
  417. // comment-out next line to force validation of all mods ignoring checksum
  418. if (newChecksum != checksum)
  419. {
  420. checksum = newChecksum;
  421. validation = PENDING;
  422. }
  423. }
  424. void CModInfo::loadLocalData(const JsonNode & data)
  425. {
  426. bool validated = false;
  427. enabled = true;
  428. checksum = 0;
  429. if (data.getType() == JsonNode::DATA_BOOL)
  430. {
  431. enabled = data.Bool();
  432. }
  433. if (data.getType() == JsonNode::DATA_STRUCT)
  434. {
  435. enabled = data["active"].Bool();
  436. validated = data["validated"].Bool();
  437. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  438. }
  439. if (enabled)
  440. validation = validated ? PASSED : PENDING;
  441. else
  442. validation = validated ? PASSED : FAILED;
  443. }
  444. CModHandler::CModHandler()
  445. {
  446. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  447. {
  448. identifiers.registerObject("core", "resource", GameConstants::RESOURCE_NAMES[i], i);
  449. }
  450. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  451. identifiers.registerObject("core", "primSkill", PrimarySkill::names[i], i);
  452. }
  453. void CModHandler::loadConfigFromFile (std::string name)
  454. {
  455. settings.data = JsonUtils::assembleFromFiles("config/" + name);
  456. const JsonNode & hardcodedFeatures = settings.data["hardcodedFeatures"];
  457. settings.MAX_HEROES_AVAILABLE_PER_PLAYER = hardcodedFeatures["MAX_HEROES_AVAILABLE_PER_PLAYER"].Float();
  458. settings.MAX_HEROES_ON_MAP_PER_PLAYER = hardcodedFeatures["MAX_HEROES_ON_MAP_PER_PLAYER"].Float();
  459. settings.CREEP_SIZE = hardcodedFeatures["CREEP_SIZE"].Float();
  460. settings.WEEKLY_GROWTH = hardcodedFeatures["WEEKLY_GROWTH_PERCENT"].Float();
  461. settings.NEUTRAL_STACK_EXP = hardcodedFeatures["NEUTRAL_STACK_EXP_DAILY"].Float();
  462. settings.MAX_BUILDING_PER_TURN = hardcodedFeatures["MAX_BUILDING_PER_TURN"].Float();
  463. settings.DWELLINGS_ACCUMULATE_CREATURES = hardcodedFeatures["DWELLINGS_ACCUMULATE_CREATURES"].Bool();
  464. settings.ALL_CREATURES_GET_DOUBLE_MONTHS = hardcodedFeatures["ALL_CREATURES_GET_DOUBLE_MONTHS"].Bool();
  465. const JsonNode & gameModules = settings.data["modules"];
  466. modules.STACK_EXP = gameModules["STACK_EXPERIENCE"].Bool();
  467. modules.STACK_ARTIFACT = gameModules["STACK_ARTIFACTS"].Bool();
  468. modules.COMMANDERS = gameModules["COMMANDERS"].Bool();
  469. modules.MITHRIL = gameModules["MITHRIL"].Bool();
  470. }
  471. // currentList is passed by value to get current list of depending mods
  472. bool CModHandler::hasCircularDependency(TModID modID, std::set <TModID> currentList) const
  473. {
  474. const CModInfo & mod = allMods.at(modID);
  475. // Mod already present? We found a loop
  476. if (vstd::contains(currentList, modID))
  477. {
  478. logGlobal->errorStream() << "Error: Circular dependency detected! Printing dependency list:";
  479. logGlobal->errorStream() << "\t" << mod.name << " -> ";
  480. return true;
  481. }
  482. currentList.insert(modID);
  483. // recursively check every dependency of this mod
  484. for(const TModID & dependency : mod.dependencies)
  485. {
  486. if (hasCircularDependency(dependency, currentList))
  487. {
  488. logGlobal->errorStream() << "\t" << mod.name << " ->\n"; // conflict detected, print dependency list
  489. return true;
  490. }
  491. }
  492. return false;
  493. }
  494. bool CModHandler::checkDependencies(const std::vector <TModID> & input) const
  495. {
  496. for(const TModID & id : input)
  497. {
  498. const CModInfo & mod = allMods.at(id);
  499. for(const TModID & dep : mod.dependencies)
  500. {
  501. if (!vstd::contains(input, dep))
  502. {
  503. logGlobal->errorStream() << "Error: Mod " << mod.name << " requires missing " << dep << "!";
  504. return false;
  505. }
  506. }
  507. for(const TModID & conflicting : mod.conflicts)
  508. {
  509. if (vstd::contains(input, conflicting))
  510. {
  511. logGlobal->errorStream() << "Error: Mod " << mod.name << " conflicts with " << allMods.at(conflicting).name << "!";
  512. return false;
  513. }
  514. }
  515. if (hasCircularDependency(id))
  516. return false;
  517. }
  518. return true;
  519. }
  520. std::vector <TModID> CModHandler::resolveDependencies(std::vector <TModID> input) const
  521. {
  522. // Topological sort algorithm
  523. // May not be the fastest one but VCMI does not needs any speed here
  524. // Unless user have dozens of mods with complex dependencies this code should be fine
  525. // first - sort input to have input strictly based on name (and not on hashmap or anything else)
  526. boost::range::sort(input);
  527. std::vector <TModID> output;
  528. output.reserve(input.size());
  529. std::set <TModID> resolvedMods;
  530. // Check if all mod dependencies are resolved (moved to resolvedMods)
  531. auto isResolved = [&](const CModInfo mod) -> bool
  532. {
  533. for(const TModID & dependency : mod.dependencies)
  534. {
  535. if (!vstd::contains(resolvedMods, dependency))
  536. return false;
  537. }
  538. return true;
  539. };
  540. while (!input.empty())
  541. {
  542. std::set <TModID> toResolve; // list of mods resolved on this iteration
  543. for (auto it = input.begin(); it != input.end();)
  544. {
  545. if (isResolved(allMods.at(*it)))
  546. {
  547. toResolve.insert(*it);
  548. output.push_back(*it);
  549. it = input.erase(it);
  550. continue;
  551. }
  552. it++;
  553. }
  554. resolvedMods.insert(toResolve.begin(), toResolve.end());
  555. }
  556. return output;
  557. }
  558. std::vector<std::string> CModHandler::getModList(std::string path)
  559. {
  560. std::string modDir = boost::to_upper_copy(path + "MODS/");
  561. size_t depth = boost::range::count(modDir, '/');
  562. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  563. {
  564. if (id.getType() != EResType::DIRECTORY)
  565. return false;
  566. if (!boost::algorithm::starts_with(id.getName(), modDir))
  567. return false;
  568. if (boost::range::count(id.getName(), '/') != depth )
  569. return false;
  570. return true;
  571. });
  572. //storage for found mods
  573. std::vector<std::string> foundMods;
  574. for (auto & entry : list)
  575. {
  576. std::string name = entry.getName();
  577. name.erase(0, modDir.size()); //Remove path prefix
  578. // check if wog is actually present. Hack-ish but better than crash
  579. // TODO: remove soon (hopefully - before 0.96)
  580. if (name == "WOG")
  581. {
  582. if (!CResourceHandler::get("initial")->existsResource(ResourceID("DATA/ZVS", EResType::DIRECTORY)) &&
  583. !CResourceHandler::get("initial")->existsResource(ResourceID("MODS/WOG/DATA/ZVS", EResType::DIRECTORY)))
  584. {
  585. continue;
  586. }
  587. }
  588. if (!name.empty())
  589. foundMods.push_back(name);
  590. }
  591. return foundMods;
  592. }
  593. void CModHandler::loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods)
  594. {
  595. for (std::string modName : getModList(path))
  596. {
  597. boost::to_lower(modName);
  598. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  599. if (CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  600. {
  601. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  602. if (!parent.empty()) // this is submod, add parent to dependecies
  603. mod.dependencies.insert(parent);
  604. allMods[modFullName] = mod;
  605. if (mod.enabled && enableMods)
  606. activeMods.push_back(modFullName);
  607. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.enabled);
  608. }
  609. }
  610. }
  611. void CModHandler::loadMods()
  612. {
  613. const JsonNode modConfig = loadModSettings("config/modSettings.json");
  614. loadMods("", "", modConfig["activeMods"], true);
  615. coreMod = CModInfo("core", modConfig["core"], JsonNode(ResourceID("config/gameConfig.json")));
  616. coreMod.name = "Original game files";
  617. }
  618. std::vector<std::string> CModHandler::getAllMods()
  619. {
  620. std::vector<std::string> modlist;
  621. for (auto & entry : allMods)
  622. modlist.push_back(entry.first);
  623. return modlist;
  624. }
  625. std::vector<std::string> CModHandler::getActiveMods()
  626. {
  627. return activeMods;
  628. }
  629. static JsonNode genDefaultFS()
  630. {
  631. // default FS config for mods: directory "Content" that acts as H3 root directory
  632. JsonNode defaultFS;
  633. defaultFS[""].Vector().resize(2);
  634. defaultFS[""].Vector()[0]["type"].String() = "zip";
  635. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  636. defaultFS[""].Vector()[1]["type"].String() = "dir";
  637. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  638. return defaultFS;
  639. }
  640. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  641. {
  642. static const JsonNode defaultFS = genDefaultFS();
  643. if (!conf["filesystem"].isNull())
  644. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  645. else
  646. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  647. }
  648. static ui32 calculateModChecksum(const std::string modName, ISimpleResourceLoader * filesystem)
  649. {
  650. boost::crc_32_type modChecksum;
  651. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  652. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  653. // second - add mod.json into checksum because filesystem does not contains this file
  654. // FIXME: remove workaround for core mod
  655. if (modName != "core")
  656. {
  657. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  658. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  659. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  660. }
  661. // third - add all detected text files from this mod into checksum
  662. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  663. {
  664. return resID.getType() == EResType::TEXT &&
  665. ( boost::starts_with(resID.getName(), "DATA") ||
  666. boost::starts_with(resID.getName(), "CONFIG"));
  667. });
  668. for (const ResourceID & file : files)
  669. {
  670. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  671. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  672. }
  673. return modChecksum.checksum();
  674. }
  675. void CModHandler::loadModFilesystems()
  676. {
  677. activeMods = resolveDependencies(activeMods);
  678. coreMod.updateChecksum(calculateModChecksum("core", CResourceHandler::get("core")));
  679. for(std::string & modName : activeMods)
  680. {
  681. CModInfo & mod = allMods[modName];
  682. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  683. }
  684. }
  685. CModInfo & CModHandler::getModData(TModID modId)
  686. {
  687. CModInfo & mod = allMods.at(modId);
  688. assert(vstd::contains(activeMods, modId)); // not really necessary but won't hurt
  689. return mod;
  690. }
  691. void CModHandler::initializeConfig()
  692. {
  693. loadConfigFromFile("defaultMods.json");
  694. }
  695. void CModHandler::load()
  696. {
  697. CStopWatch totalTime, timer;
  698. CContentHandler content;
  699. logGlobal->infoStream() << "\tInitializing content handler: " << timer.getDiff() << " ms";
  700. for(const TModID & modName : activeMods)
  701. {
  702. logGlobal->traceStream() << "Generating checksum for " << modName;
  703. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  704. }
  705. // first - load virtual "core" mod that contains all data
  706. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  707. content.preloadData(coreMod);
  708. for(const TModID & modName : activeMods)
  709. content.preloadData(allMods[modName]);
  710. logGlobal->infoStream() << "\tParsing mod data: " << timer.getDiff() << " ms";
  711. content.load(coreMod);
  712. for(const TModID & modName : activeMods)
  713. content.load(allMods[modName]);
  714. logGlobal->infoStream() << "\tLoading mod data: " << timer.getDiff() << "ms";
  715. VLC->creh->loadCrExpBon();
  716. VLC->creh->buildBonusTreeForTiers(); //do that after all new creatures are loaded
  717. identifiers.finalize();
  718. logGlobal->infoStream() << "\tResolving identifiers: " << timer.getDiff() << " ms";
  719. content.afterLoadFinalization();
  720. logGlobal->infoStream() << "\tHandlers post-load finalization: " << timer.getDiff() << " ms";
  721. logGlobal->infoStream() << "\tAll game content loaded in " << totalTime.getDiff() << " ms";
  722. }
  723. void CModHandler::afterLoad()
  724. {
  725. JsonNode modSettings;
  726. for (auto & modEntry : allMods)
  727. {
  728. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  729. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  730. }
  731. modSettings["core"] = coreMod.saveLocalData();
  732. std::ofstream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::trunc);
  733. file << modSettings;
  734. }