CModHandler.cpp 26 KB

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