CModHandler.cpp 30 KB

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