CModHandler.cpp 30 KB

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