CModHandler.cpp 26 KB

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