CModHandler.cpp 32 KB

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