CModHandler.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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 "GameConstants.h"
  11. #include "StdInc.h"
  12. #include "CModHandler.h"
  13. #include "mapObjects/CObjectClassesHandler.h"
  14. #include "rmg/CRmgTemplateStorage.h"
  15. #include "filesystem/FileStream.h"
  16. #include "filesystem/AdapterLoaders.h"
  17. #include "filesystem/CFilesystemLoader.h"
  18. #include "filesystem/Filesystem.h"
  19. #include "CCreatureHandler.h"
  20. #include "CArtHandler.h"
  21. #include "CTownHandler.h"
  22. #include "CHeroHandler.h"
  23. #include "mapObjects/CObjectHandler.h"
  24. #include "StringConstants.h"
  25. #include "CStopWatch.h"
  26. #include "IHandlerBase.h"
  27. #include "spells/CSpellHandler.h"
  28. #include "CSkillHandler.h"
  29. #include "CGeneralTextHandler.h"
  30. #include "Languages.h"
  31. #include "ScriptHandler.h"
  32. #include "RoadHandler.h"
  33. #include "GameSettings.h"
  34. #include "RiverHandler.h"
  35. #include "TerrainHandler.h"
  36. #include "BattleFieldHandler.h"
  37. #include "ObstacleHandler.h"
  38. #include <vstd/StringUtils.h>
  39. VCMI_LIB_NAMESPACE_BEGIN
  40. CIdentifierStorage::CIdentifierStorage():
  41. state(LOADING)
  42. {
  43. }
  44. void CIdentifierStorage::checkIdentifier(std::string & ID)
  45. {
  46. if (boost::algorithm::ends_with(ID, "."))
  47. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  48. else
  49. {
  50. size_t pos = 0;
  51. do
  52. {
  53. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  54. {
  55. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  56. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  57. }
  58. pos = ID.find('.', pos);
  59. }
  60. while(pos++ != std::string::npos);
  61. }
  62. }
  63. void CIdentifierStorage::requestIdentifier(ObjectCallback callback)
  64. {
  65. checkIdentifier(callback.type);
  66. checkIdentifier(callback.name);
  67. assert(!callback.localScope.empty());
  68. if (state != FINISHED) // enqueue request if loading is still in progress
  69. scheduledRequests.push_back(callback);
  70. else // execute immediately for "late" requests
  71. resolveIdentifier(callback);
  72. }
  73. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  74. {
  75. assert(!scope.empty());
  76. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  77. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  78. if (scope == scopeAndFullName.first)
  79. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  80. ObjectCallback result;
  81. result.localScope = scope;
  82. result.remoteScope = scopeAndFullName.first;
  83. result.type = typeAndName.first;
  84. result.name = typeAndName.second;
  85. result.callback = callback;
  86. result.optional = optional;
  87. return result;
  88. }
  89. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameAndType(const std::string & scope, const std::string & type, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  90. {
  91. assert(!scope.empty());
  92. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  93. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  94. if(!typeAndName.first.empty())
  95. {
  96. if (typeAndName.first != type)
  97. logMod->error("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  98. else
  99. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  100. }
  101. if (scope == scopeAndFullName.first)
  102. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  103. ObjectCallback result;
  104. result.localScope = scope;
  105. result.remoteScope = scopeAndFullName.first;
  106. result.type = type;
  107. result.name = typeAndName.second;
  108. result.callback = callback;
  109. result.optional = optional;
  110. return result;
  111. }
  112. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback)
  113. {
  114. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  115. }
  116. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback)
  117. {
  118. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  119. }
  120. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback)
  121. {
  122. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, false));
  123. }
  124. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback)
  125. {
  126. requestIdentifier(ObjectCallback::fromNameWithType(name.meta, name.String(), callback, false));
  127. }
  128. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback)
  129. {
  130. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  131. }
  132. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback)
  133. {
  134. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
  135. }
  136. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent)
  137. {
  138. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent));
  139. if (idList.size() == 1)
  140. return idList.front().id;
  141. if (!silent)
  142. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  143. return std::optional<si32>();
  144. }
  145. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent)
  146. {
  147. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent));
  148. if (idList.size() == 1)
  149. return idList.front().id;
  150. if (!silent)
  151. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  152. return std::optional<si32>();
  153. }
  154. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent)
  155. {
  156. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent));
  157. if (idList.size() == 1)
  158. return idList.front().id;
  159. if (!silent)
  160. logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta);
  161. return std::optional<si32>();
  162. }
  163. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent)
  164. {
  165. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent));
  166. if (idList.size() == 1)
  167. return idList.front().id;
  168. if (!silent)
  169. logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope);
  170. return std::optional<si32>();
  171. }
  172. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  173. {
  174. ObjectData data;
  175. data.scope = scope;
  176. data.id = identifier;
  177. std::string fullID = type + '.' + name;
  178. checkIdentifier(fullID);
  179. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  180. if(!vstd::containsMapping(registeredObjects, mapping))
  181. {
  182. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  183. registeredObjects.insert(mapping);
  184. }
  185. }
  186. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request)
  187. {
  188. std::set<std::string> allowedScopes;
  189. bool isValidScope = true;
  190. // called have not specified destination mod explicitly
  191. if (request.remoteScope.empty())
  192. {
  193. // special scope that should have access to all in-game objects
  194. if (request.localScope == CModHandler::scopeGame())
  195. {
  196. for(const auto & modName : VLC->modh->getActiveMods())
  197. allowedScopes.insert(modName);
  198. }
  199. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  200. else if(request.localScope != CModHandler::scopeBuiltin() && !request.localScope.empty())
  201. {
  202. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  203. if(!isValidScope)
  204. return std::vector<ObjectData>();
  205. allowedScopes.insert(request.localScope);
  206. }
  207. // all mods can access built-in mod
  208. allowedScopes.insert(CModHandler::scopeBuiltin());
  209. }
  210. else
  211. {
  212. //if destination mod was specified explicitly, restrict lookup to this mod
  213. if(request.remoteScope == CModHandler::scopeBuiltin() )
  214. {
  215. //built-in mod is an implicit dependency for all mods, allow access into it
  216. allowedScopes.insert(request.remoteScope);
  217. }
  218. else if ( request.localScope == CModHandler::scopeGame() )
  219. {
  220. // allow access, this is special scope that should have access to all in-game objects
  221. allowedScopes.insert(request.remoteScope);
  222. }
  223. else if(request.remoteScope == request.localScope )
  224. {
  225. // allow self-access
  226. allowedScopes.insert(request.remoteScope);
  227. }
  228. else
  229. {
  230. // allow access only if mod is in our dependencies
  231. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  232. if(!isValidScope)
  233. return std::vector<ObjectData>();
  234. if(myDeps.count(request.remoteScope))
  235. allowedScopes.insert(request.remoteScope);
  236. }
  237. }
  238. std::string fullID = request.type + '.' + request.name;
  239. auto entries = registeredObjects.equal_range(fullID);
  240. if (entries.first != entries.second)
  241. {
  242. std::vector<ObjectData> locatedIDs;
  243. for (auto it = entries.first; it != entries.second; it++)
  244. {
  245. if (vstd::contains(allowedScopes, it->second.scope))
  246. {
  247. locatedIDs.push_back(it->second);
  248. }
  249. }
  250. return locatedIDs;
  251. }
  252. return std::vector<ObjectData>();
  253. }
  254. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request)
  255. {
  256. auto identifiers = getPossibleIdentifiers(request);
  257. if (identifiers.size() == 1) // normally resolved ID
  258. {
  259. request.callback(identifiers.front().id);
  260. return true;
  261. }
  262. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  263. {
  264. return true;
  265. }
  266. // error found. Try to generate some debug info
  267. if(identifiers.empty())
  268. logMod->error("Unknown identifier!");
  269. else
  270. logMod->error("Ambiguous identifier request!");
  271. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  272. for(const auto & id : identifiers)
  273. {
  274. logMod->error("\tID is available in mod %s", id.scope);
  275. }
  276. return false;
  277. }
  278. void CIdentifierStorage::finalize()
  279. {
  280. state = FINALIZING;
  281. bool errorsFound = false;
  282. while ( !scheduledRequests.empty() )
  283. {
  284. // Use local copy since new requests may appear during resolving, invalidating any iterators
  285. auto request = scheduledRequests.back();
  286. scheduledRequests.pop_back();
  287. if (!resolveIdentifier(request))
  288. errorsFound = true;
  289. }
  290. if (errorsFound)
  291. {
  292. for(const auto & object : registeredObjects)
  293. {
  294. logMod->trace("%s : %s -> %d", object.second.scope, object.first, object.second.id);
  295. }
  296. logMod->error("All known identifiers were dumped into log file");
  297. }
  298. assert(errorsFound == false);
  299. state = FINISHED;
  300. }
  301. ContentTypeHandler::ContentTypeHandler(IHandlerBase * handler, const std::string & objectName):
  302. handler(handler),
  303. objectName(objectName),
  304. originalData(handler->loadLegacyData())
  305. {
  306. for(auto & node : originalData)
  307. {
  308. node.setMeta(CModHandler::scopeBuiltin());
  309. }
  310. }
  311. bool ContentTypeHandler::preloadModData(const std::string & modName, const std::vector<std::string> & fileList, bool validate)
  312. {
  313. bool result = false;
  314. JsonNode data = JsonUtils::assembleFromFiles(fileList, result);
  315. data.setMeta(modName);
  316. ModInfo & modInfo = modData[modName];
  317. for(auto entry : data.Struct())
  318. {
  319. size_t colon = entry.first.find(':');
  320. if (colon == std::string::npos)
  321. {
  322. // normal object, local to this mod
  323. modInfo.modData[entry.first].swap(entry.second);
  324. }
  325. else
  326. {
  327. std::string remoteName = entry.first.substr(0, colon);
  328. std::string objectName = entry.first.substr(colon + 1);
  329. // patching this mod? Send warning and continue - this situation can be handled normally
  330. if (remoteName == modName)
  331. logMod->warn("Redundant namespace definition for %s", objectName);
  332. logMod->trace("Patching object %s (%s) from %s", objectName, remoteName, modName);
  333. JsonNode & remoteConf = modData[remoteName].patches[objectName];
  334. JsonUtils::merge(remoteConf, entry.second);
  335. }
  336. }
  337. return result;
  338. }
  339. bool ContentTypeHandler::loadMod(const std::string & modName, bool validate)
  340. {
  341. ModInfo & modInfo = modData[modName];
  342. bool result = true;
  343. auto performValidate = [&,this](JsonNode & data, const std::string & name){
  344. handler->beforeValidate(data);
  345. if (validate)
  346. result &= JsonUtils::validate(data, "vcmi:" + objectName, name);
  347. };
  348. // apply patches
  349. if (!modInfo.patches.isNull())
  350. JsonUtils::merge(modInfo.modData, modInfo.patches);
  351. for(auto & entry : modInfo.modData.Struct())
  352. {
  353. const std::string & name = entry.first;
  354. JsonNode & data = entry.second;
  355. if (vstd::contains(data.Struct(), "index") && !data["index"].isNull())
  356. {
  357. if (modName != "core")
  358. logMod->warn("Mod %s is attempting to load original data! This should be reserved for built-in mod.", modName);
  359. // try to add H3 object data
  360. size_t index = static_cast<size_t>(data["index"].Float());
  361. if(originalData.size() > index)
  362. {
  363. logMod->trace("found original data in loadMod(%s) at index %d", name, index);
  364. JsonUtils::merge(originalData[index], data);
  365. std::swap(originalData[index], data);
  366. originalData[index].clear(); // do not use same data twice (same ID)
  367. }
  368. else
  369. {
  370. logMod->trace("no original data in loadMod(%s) at index %d", name, index);
  371. }
  372. performValidate(data, name);
  373. handler->loadObject(modName, name, data, index);
  374. }
  375. else
  376. {
  377. // normal new object
  378. logMod->trace("no index in loadMod(%s)", name);
  379. performValidate(data,name);
  380. handler->loadObject(modName, name, data);
  381. }
  382. }
  383. return result;
  384. }
  385. void ContentTypeHandler::loadCustom()
  386. {
  387. handler->loadCustom();
  388. }
  389. void ContentTypeHandler::afterLoadFinalization()
  390. {
  391. handler->afterLoadFinalization();
  392. }
  393. void CContentHandler::init()
  394. {
  395. handlers.insert(std::make_pair("heroClasses", ContentTypeHandler(&VLC->heroh->classes, "heroClass")));
  396. handlers.insert(std::make_pair("artifacts", ContentTypeHandler(VLC->arth, "artifact")));
  397. handlers.insert(std::make_pair("creatures", ContentTypeHandler(VLC->creh, "creature")));
  398. handlers.insert(std::make_pair("factions", ContentTypeHandler(VLC->townh, "faction")));
  399. handlers.insert(std::make_pair("objects", ContentTypeHandler(VLC->objtypeh, "object")));
  400. handlers.insert(std::make_pair("heroes", ContentTypeHandler(VLC->heroh, "hero")));
  401. handlers.insert(std::make_pair("spells", ContentTypeHandler(VLC->spellh, "spell")));
  402. handlers.insert(std::make_pair("skills", ContentTypeHandler(VLC->skillh, "skill")));
  403. handlers.insert(std::make_pair("templates", ContentTypeHandler(VLC->tplh, "template")));
  404. #if SCRIPTING_ENABLED
  405. handlers.insert(std::make_pair("scripts", ContentTypeHandler(VLC->scriptHandler, "script")));
  406. #endif
  407. handlers.insert(std::make_pair("battlefields", ContentTypeHandler(VLC->battlefieldsHandler, "battlefield")));
  408. handlers.insert(std::make_pair("terrains", ContentTypeHandler(VLC->terrainTypeHandler, "terrain")));
  409. handlers.insert(std::make_pair("rivers", ContentTypeHandler(VLC->riverTypeHandler, "river")));
  410. handlers.insert(std::make_pair("roads", ContentTypeHandler(VLC->roadTypeHandler, "road")));
  411. handlers.insert(std::make_pair("obstacles", ContentTypeHandler(VLC->obstacleHandler, "obstacle")));
  412. //TODO: any other types of moddables?
  413. }
  414. bool CContentHandler::preloadModData(const std::string & modName, JsonNode modConfig, bool validate)
  415. {
  416. bool result = true;
  417. for(auto & handler : handlers)
  418. {
  419. result &= handler.second.preloadModData(modName, modConfig[handler.first].convertTo<std::vector<std::string> >(), validate);
  420. }
  421. return result;
  422. }
  423. bool CContentHandler::loadMod(const std::string & modName, bool validate)
  424. {
  425. bool result = true;
  426. for(auto & handler : handlers)
  427. {
  428. result &= handler.second.loadMod(modName, validate);
  429. }
  430. return result;
  431. }
  432. void CContentHandler::loadCustom()
  433. {
  434. for(auto & handler : handlers)
  435. {
  436. handler.second.loadCustom();
  437. }
  438. }
  439. void CContentHandler::afterLoadFinalization()
  440. {
  441. for(auto & handler : handlers)
  442. {
  443. handler.second.afterLoadFinalization();
  444. }
  445. }
  446. void CContentHandler::preloadData(CModInfo & mod)
  447. {
  448. bool validate = (mod.validation != CModInfo::PASSED);
  449. // print message in format [<8-symbols checksum>] <modname>
  450. logMod->info("\t\t[%08x]%s", mod.checksum, mod.name);
  451. if (validate && mod.identifier != CModHandler::scopeBuiltin())
  452. {
  453. if (!JsonUtils::validate(mod.config, "vcmi:mod", mod.identifier))
  454. mod.validation = CModInfo::FAILED;
  455. }
  456. if (!preloadModData(mod.identifier, mod.config, validate))
  457. mod.validation = CModInfo::FAILED;
  458. }
  459. void CContentHandler::load(CModInfo & mod)
  460. {
  461. bool validate = (mod.validation != CModInfo::PASSED);
  462. if (!loadMod(mod.identifier, validate))
  463. mod.validation = CModInfo::FAILED;
  464. if (validate)
  465. {
  466. if (mod.validation != CModInfo::FAILED)
  467. logMod->info("\t\t[DONE] %s", mod.name);
  468. else
  469. logMod->error("\t\t[FAIL] %s", mod.name);
  470. }
  471. else
  472. logMod->info("\t\t[SKIP] %s", mod.name);
  473. }
  474. const ContentTypeHandler & CContentHandler::operator[](const std::string & name) const
  475. {
  476. return handlers.at(name);
  477. }
  478. static JsonNode loadModSettings(const std::string & path)
  479. {
  480. if (CResourceHandler::get("local")->existsResource(ResourceID(path)))
  481. {
  482. return JsonNode(ResourceID(path, EResType::TEXT));
  483. }
  484. // Probably new install. Create initial configuration
  485. CResourceHandler::get("local")->createResource(path);
  486. return JsonNode();
  487. }
  488. JsonNode addMeta(JsonNode config, const std::string & meta)
  489. {
  490. config.setMeta(meta);
  491. return config;
  492. }
  493. CModInfo::Version CModInfo::Version::GameVersion()
  494. {
  495. return Version(VCMI_VERSION_MAJOR, VCMI_VERSION_MINOR, VCMI_VERSION_PATCH);
  496. }
  497. CModInfo::Version CModInfo::Version::fromString(std::string from)
  498. {
  499. int major = 0;
  500. int minor = 0;
  501. int patch = 0;
  502. try
  503. {
  504. auto pointPos = from.find('.');
  505. major = std::stoi(from.substr(0, pointPos));
  506. if(pointPos != std::string::npos)
  507. {
  508. from = from.substr(pointPos + 1);
  509. pointPos = from.find('.');
  510. minor = std::stoi(from.substr(0, pointPos));
  511. if(pointPos != std::string::npos)
  512. patch = std::stoi(from.substr(pointPos + 1));
  513. }
  514. }
  515. catch(const std::invalid_argument &)
  516. {
  517. return Version();
  518. }
  519. return Version(major, minor, patch);
  520. }
  521. std::string CModInfo::Version::toString() const
  522. {
  523. return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
  524. }
  525. bool CModInfo::Version::compatible(const Version & other, bool checkMinor, bool checkPatch) const
  526. {
  527. return (major == other.major &&
  528. (!checkMinor || minor >= other.minor) &&
  529. (!checkPatch || minor > other.minor || (minor == other.minor && patch >= other.patch)));
  530. }
  531. bool CModInfo::Version::isNull() const
  532. {
  533. return major == 0 && minor == 0 && patch == 0;
  534. }
  535. CModInfo::CModInfo():
  536. checksum(0),
  537. explicitlyEnabled(false),
  538. implicitlyEnabled(true),
  539. validation(PENDING)
  540. {
  541. }
  542. CModInfo::CModInfo(const std::string & identifier, const JsonNode & local, const JsonNode & config):
  543. identifier(identifier),
  544. name(config["name"].String()),
  545. description(config["description"].String()),
  546. dependencies(config["depends"].convertTo<std::set<std::string>>()),
  547. conflicts(config["conflicts"].convertTo<std::set<std::string>>()),
  548. checksum(0),
  549. explicitlyEnabled(false),
  550. implicitlyEnabled(true),
  551. validation(PENDING),
  552. config(addMeta(config, identifier))
  553. {
  554. version = Version::fromString(config["version"].String());
  555. if(!config["compatibility"].isNull())
  556. {
  557. vcmiCompatibleMin = Version::fromString(config["compatibility"]["min"].String());
  558. vcmiCompatibleMax = Version::fromString(config["compatibility"]["max"].String());
  559. }
  560. if (!config["language"].isNull())
  561. baseLanguage = config["language"].String();
  562. else
  563. baseLanguage = "english";
  564. loadLocalData(local);
  565. }
  566. JsonNode CModInfo::saveLocalData() const
  567. {
  568. std::ostringstream stream;
  569. stream << std::noshowbase << std::hex << std::setw(8) << std::setfill('0') << checksum;
  570. JsonNode conf;
  571. conf["active"].Bool() = explicitlyEnabled;
  572. conf["validated"].Bool() = validation != FAILED;
  573. conf["checksum"].String() = stream.str();
  574. return conf;
  575. }
  576. std::string CModInfo::getModDir(const std::string & name)
  577. {
  578. return "MODS/" + boost::algorithm::replace_all_copy(name, ".", "/MODS/");
  579. }
  580. std::string CModInfo::getModFile(const std::string & name)
  581. {
  582. return getModDir(name) + "/mod.json";
  583. }
  584. void CModInfo::updateChecksum(ui32 newChecksum)
  585. {
  586. // comment-out next line to force validation of all mods ignoring checksum
  587. if (newChecksum != checksum)
  588. {
  589. checksum = newChecksum;
  590. validation = PENDING;
  591. }
  592. }
  593. void CModInfo::loadLocalData(const JsonNode & data)
  594. {
  595. bool validated = false;
  596. implicitlyEnabled = true;
  597. explicitlyEnabled = !config["keepDisabled"].Bool();
  598. checksum = 0;
  599. if (data.getType() == JsonNode::JsonType::DATA_BOOL)
  600. {
  601. explicitlyEnabled = data.Bool();
  602. }
  603. if (data.getType() == JsonNode::JsonType::DATA_STRUCT)
  604. {
  605. explicitlyEnabled = data["active"].Bool();
  606. validated = data["validated"].Bool();
  607. checksum = strtol(data["checksum"].String().c_str(), nullptr, 16);
  608. }
  609. //check compatibility
  610. implicitlyEnabled &= (vcmiCompatibleMin.isNull() || Version::GameVersion().compatible(vcmiCompatibleMin));
  611. implicitlyEnabled &= (vcmiCompatibleMax.isNull() || vcmiCompatibleMax.compatible(Version::GameVersion()));
  612. if(!implicitlyEnabled)
  613. logGlobal->warn("Mod %s is incompatible with current version of VCMI and cannot be enabled", name);
  614. if (boost::iequals(config["modType"].String(), "translation")) // compatibility code - mods use "Translation" type at the moment
  615. {
  616. if (baseLanguage != VLC->generaltexth->getPreferredLanguage())
  617. {
  618. logGlobal->warn("Translation mod %s was not loaded: language mismatch!", name);
  619. implicitlyEnabled = false;
  620. }
  621. }
  622. if (isEnabled())
  623. validation = validated ? PASSED : PENDING;
  624. else
  625. validation = validated ? PASSED : FAILED;
  626. }
  627. bool CModInfo::isEnabled() const
  628. {
  629. return implicitlyEnabled && explicitlyEnabled;
  630. }
  631. void CModInfo::setEnabled(bool on)
  632. {
  633. explicitlyEnabled = on;
  634. }
  635. CModHandler::CModHandler() : content(std::make_shared<CContentHandler>())
  636. {
  637. //TODO: moddable spell schools
  638. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  639. identifiers.registerObject(CModHandler::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id);
  640. identifiers.registerObject(CModHandler::scopeBuiltin(), "spellSchool", "any", SpellSchool(ESpellSchool::ANY));
  641. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  642. {
  643. identifiers.registerObject(CModHandler::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  644. }
  645. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  646. {
  647. identifiers.registerObject(CModHandler::scopeBuiltin(), "primSkill", PrimarySkill::names[i], i);
  648. identifiers.registerObject(CModHandler::scopeBuiltin(), "primarySkill", PrimarySkill::names[i], i);
  649. }
  650. }
  651. // currentList is passed by value to get current list of depending mods
  652. bool CModHandler::hasCircularDependency(const TModID & modID, std::set<TModID> currentList) const
  653. {
  654. const CModInfo & mod = allMods.at(modID);
  655. // Mod already present? We found a loop
  656. if (vstd::contains(currentList, modID))
  657. {
  658. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  659. logMod->error("\t%s -> ", mod.name);
  660. return true;
  661. }
  662. currentList.insert(modID);
  663. // recursively check every dependency of this mod
  664. for(const TModID & dependency : mod.dependencies)
  665. {
  666. if (hasCircularDependency(dependency, currentList))
  667. {
  668. logMod->error("\t%s ->\n", mod.name); // conflict detected, print dependency list
  669. return true;
  670. }
  671. }
  672. return false;
  673. }
  674. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  675. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  676. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  677. {
  678. // Topological sort algorithm.
  679. // TODO: Investigate possible ways to improve performance.
  680. boost::range::sort(modsToResolve); // Sort mods per name
  681. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  682. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  683. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  684. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  685. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  686. {
  687. if(mod.dependencies.size() > resolvedModIDs.size())
  688. return CModInfo::PENDING;
  689. for(const TModID & dependency : mod.dependencies)
  690. {
  691. if(!vstd::contains(resolvedModIDs, dependency))
  692. return CModInfo::PENDING;
  693. }
  694. return CModInfo::PASSED;
  695. };
  696. while(true)
  697. {
  698. std::set <TModID> resolvedOnCurrentTreeLevel;
  699. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  700. {
  701. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  702. {
  703. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  704. sortedValidMods.push_back(*it);
  705. it = modsToResolve.erase(it);
  706. continue;
  707. }
  708. it++;
  709. }
  710. if(!resolvedOnCurrentTreeLevel.empty())
  711. {
  712. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  713. continue;
  714. }
  715. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  716. break;
  717. }
  718. // Left mods have unresolved dependencies, output all to log.
  719. for(const auto & brokenModID : modsToResolve)
  720. {
  721. const CModInfo & brokenMod = allMods.at(brokenModID);
  722. for(const TModID & dependency : brokenMod.dependencies)
  723. {
  724. if(!vstd::contains(resolvedModIDs, dependency))
  725. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.name, dependency);
  726. }
  727. }
  728. return sortedValidMods;
  729. }
  730. std::vector<std::string> CModHandler::getModList(const std::string & path) const
  731. {
  732. std::string modDir = boost::to_upper_copy(path + "MODS/");
  733. size_t depth = boost::range::count(modDir, '/');
  734. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourceID & id) -> bool
  735. {
  736. if (id.getType() != EResType::DIRECTORY)
  737. return false;
  738. if (!boost::algorithm::starts_with(id.getName(), modDir))
  739. return false;
  740. if (boost::range::count(id.getName(), '/') != depth )
  741. return false;
  742. return true;
  743. });
  744. //storage for found mods
  745. std::vector<std::string> foundMods;
  746. for(const auto & entry : list)
  747. {
  748. std::string name = entry.getName();
  749. name.erase(0, modDir.size()); //Remove path prefix
  750. if (!name.empty())
  751. foundMods.push_back(name);
  752. }
  753. return foundMods;
  754. }
  755. bool CModHandler::isScopeReserved(const TModID & scope)
  756. {
  757. //following scopes are reserved - either in use by mod system or by filesystem
  758. static const std::array<TModID, 9> reservedScopes = {
  759. "core", "map", "game", "root", "saves", "config", "local", "initial", "mapEditor"
  760. };
  761. return std::find(reservedScopes.begin(), reservedScopes.end(), scope) != reservedScopes.end();
  762. }
  763. const TModID & CModHandler::scopeBuiltin()
  764. {
  765. static const TModID scope = "core";
  766. return scope;
  767. }
  768. const TModID & CModHandler::scopeGame()
  769. {
  770. static const TModID scope = "game";
  771. return scope;
  772. }
  773. const TModID & CModHandler::scopeMap()
  774. {
  775. //TODO: implement accessing map dependencies for both H3 and VCMI maps
  776. // for now, allow access to any identifiers
  777. static const TModID scope = "game";
  778. return scope;
  779. }
  780. void CModHandler::loadMods(const std::string & path, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  781. {
  782. for(const std::string & modName : getModList(path))
  783. loadOneMod(modName, parent, modSettings, enableMods);
  784. }
  785. void CModHandler::loadOneMod(std::string modName, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  786. {
  787. boost::to_lower(modName);
  788. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  789. if ( isScopeReserved(modFullName))
  790. {
  791. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  792. return;
  793. }
  794. if(CResourceHandler::get("initial")->existsResource(ResourceID(CModInfo::getModFile(modFullName))))
  795. {
  796. CModInfo mod(modFullName, modSettings[modName], JsonNode(ResourceID(CModInfo::getModFile(modFullName))));
  797. if (!parent.empty()) // this is submod, add parent to dependencies
  798. mod.dependencies.insert(parent);
  799. allMods[modFullName] = mod;
  800. if (mod.isEnabled() && enableMods)
  801. activeMods.push_back(modFullName);
  802. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  803. }
  804. }
  805. void CModHandler::loadMods(bool onlyEssential)
  806. {
  807. JsonNode modConfig;
  808. if(onlyEssential)
  809. {
  810. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  811. }
  812. else
  813. {
  814. modConfig = loadModSettings("config/modSettings.json");
  815. loadMods("", "", modConfig["activeMods"], true);
  816. }
  817. coreMod = CModInfo(CModHandler::scopeBuiltin(), modConfig[CModHandler::scopeBuiltin()], JsonNode(ResourceID("config/gameConfig.json")));
  818. coreMod.name = "Original game files";
  819. }
  820. std::vector<std::string> CModHandler::getAllMods()
  821. {
  822. std::vector<std::string> modlist;
  823. modlist.reserve(allMods.size());
  824. for (auto & entry : allMods)
  825. modlist.push_back(entry.first);
  826. return modlist;
  827. }
  828. std::vector<std::string> CModHandler::getActiveMods()
  829. {
  830. return activeMods;
  831. }
  832. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  833. {
  834. return allMods.at(modId);
  835. }
  836. static JsonNode genDefaultFS()
  837. {
  838. // default FS config for mods: directory "Content" that acts as H3 root directory
  839. JsonNode defaultFS;
  840. defaultFS[""].Vector().resize(2);
  841. defaultFS[""].Vector()[0]["type"].String() = "zip";
  842. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  843. defaultFS[""].Vector()[1]["type"].String() = "dir";
  844. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  845. return defaultFS;
  846. }
  847. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  848. {
  849. static const JsonNode defaultFS = genDefaultFS();
  850. if (!conf["filesystem"].isNull())
  851. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  852. else
  853. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  854. }
  855. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  856. {
  857. boost::crc_32_type modChecksum;
  858. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  859. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  860. // second - add mod.json into checksum because filesystem does not contains this file
  861. // FIXME: remove workaround for core mod
  862. if (modName != CModHandler::scopeBuiltin())
  863. {
  864. ResourceID modConfFile(CModInfo::getModFile(modName), EResType::TEXT);
  865. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  866. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  867. }
  868. // third - add all detected text files from this mod into checksum
  869. auto files = filesystem->getFilteredFiles([](const ResourceID & resID)
  870. {
  871. return resID.getType() == EResType::TEXT &&
  872. ( boost::starts_with(resID.getName(), "DATA") ||
  873. boost::starts_with(resID.getName(), "CONFIG"));
  874. });
  875. for (const ResourceID & file : files)
  876. {
  877. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  878. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  879. }
  880. return modChecksum.checksum();
  881. }
  882. void CModHandler::loadModFilesystems()
  883. {
  884. CGeneralTextHandler::detectInstallParameters();
  885. activeMods = validateAndSortDependencies(activeMods);
  886. coreMod.updateChecksum(calculateModChecksum(CModHandler::scopeBuiltin(), CResourceHandler::get(CModHandler::scopeBuiltin())));
  887. for(std::string & modName : activeMods)
  888. {
  889. CModInfo & mod = allMods[modName];
  890. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  891. }
  892. }
  893. TModID CModHandler::findResourceOrigin(const ResourceID & name)
  894. {
  895. for(const auto & modID : boost::adaptors::reverse(activeMods))
  896. {
  897. if(CResourceHandler::get(modID)->existsResource(name))
  898. return modID;
  899. }
  900. if(CResourceHandler::get("core")->existsResource(name))
  901. return "core";
  902. if(CResourceHandler::get("mapEditor")->existsResource(name))
  903. return "core"; // Workaround for loading maps via map editor
  904. assert(0);
  905. return "";
  906. }
  907. std::string CModHandler::getModLanguage(const TModID& modId) const
  908. {
  909. if ( modId == "core")
  910. return VLC->generaltexth->getInstalledLanguage();
  911. return allMods.at(modId).baseLanguage;
  912. }
  913. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  914. {
  915. auto it = allMods.find(modId);
  916. isModFound = (it != allMods.end());
  917. if(isModFound)
  918. return it->second.dependencies;
  919. logMod->error("Mod not found: '%s'", modId);
  920. return {};
  921. }
  922. void CModHandler::initializeConfig()
  923. {
  924. VLC->settingsHandler->load(coreMod.config["settings"]);
  925. for(const TModID & modName : activeMods)
  926. {
  927. const auto & mod = allMods[modName];
  928. if (!mod.config["settings"].isNull())
  929. VLC->settingsHandler->load(mod.config["settings"]);
  930. }
  931. }
  932. bool CModHandler::validateTranslations(TModID modName) const
  933. {
  934. bool result = true;
  935. const auto & mod = allMods.at(modName);
  936. {
  937. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  938. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  939. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  940. }
  941. for(const auto & language : Languages::getLanguageList())
  942. {
  943. if (!language.hasTranslation)
  944. continue;
  945. if (mod.config[language.identifier].isNull())
  946. continue;
  947. if (mod.config[language.identifier]["skipValidation"].Bool())
  948. continue;
  949. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  950. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  951. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  952. }
  953. return result;
  954. }
  955. void CModHandler::loadTranslation(const TModID & modName)
  956. {
  957. const auto & mod = allMods[modName];
  958. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  959. std::string modBaseLanguage = allMods[modName].baseLanguage;
  960. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  961. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  962. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  963. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  964. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  965. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  966. }
  967. void CModHandler::load()
  968. {
  969. CStopWatch totalTime;
  970. CStopWatch timer;
  971. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  972. content->init();
  973. for(const TModID & modName : activeMods)
  974. {
  975. logMod->trace("Generating checksum for %s", modName);
  976. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  977. }
  978. // first - load virtual builtin mod that contains all data
  979. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  980. content->preloadData(coreMod);
  981. for(const TModID & modName : activeMods)
  982. content->preloadData(allMods[modName]);
  983. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  984. content->load(coreMod);
  985. for(const TModID & modName : activeMods)
  986. content->load(allMods[modName]);
  987. #if SCRIPTING_ENABLED
  988. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  989. #endif
  990. content->loadCustom();
  991. for(const TModID & modName : activeMods)
  992. loadTranslation(modName);
  993. for(const TModID & modName : activeMods)
  994. if (!validateTranslations(modName))
  995. allMods[modName].validation = CModInfo::FAILED;
  996. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  997. VLC->creh->loadCrExpMod();
  998. identifiers.finalize();
  999. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  1000. content->afterLoadFinalization();
  1001. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  1002. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  1003. }
  1004. void CModHandler::afterLoad(bool onlyEssential)
  1005. {
  1006. JsonNode modSettings;
  1007. for (auto & modEntry : allMods)
  1008. {
  1009. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  1010. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  1011. }
  1012. modSettings[CModHandler::scopeBuiltin()] = coreMod.saveLocalData();
  1013. if(!onlyEssential)
  1014. {
  1015. FileStream file(*CResourceHandler::get()->getResourceName(ResourceID("config/modSettings.json")), std::ofstream::out | std::ofstream::trunc);
  1016. file << modSettings.toJson();
  1017. }
  1018. }
  1019. std::string CModHandler::normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier)
  1020. {
  1021. auto p = vstd::splitStringToPair(identifier, ':');
  1022. if(p.first.empty())
  1023. p.first = scope;
  1024. if(p.first == remoteScope)
  1025. p.first.clear();
  1026. return p.first.empty() ? p.second : p.first + ":" + p.second;
  1027. }
  1028. void CModHandler::parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier)
  1029. {
  1030. auto p = vstd::splitStringToPair(fullIdentifier, ':');
  1031. scope = p.first;
  1032. auto p2 = vstd::splitStringToPair(p.second, '.');
  1033. if(!p2.first.empty())
  1034. {
  1035. type = p2.first;
  1036. identifier = p2.second;
  1037. }
  1038. else
  1039. {
  1040. type = p.second;
  1041. identifier.clear();
  1042. }
  1043. }
  1044. std::string CModHandler::makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier)
  1045. {
  1046. if(type.empty())
  1047. logGlobal->error("Full identifier (%s %s) requires type name", scope, identifier);
  1048. std::string actualScope = scope;
  1049. std::string actualName = identifier;
  1050. //ignore scope if identifier is scoped
  1051. auto scopeAndName = vstd::splitStringToPair(identifier, ':');
  1052. if(!scopeAndName.first.empty())
  1053. {
  1054. actualScope = scopeAndName.first;
  1055. actualName = scopeAndName.second;
  1056. }
  1057. if(actualScope.empty())
  1058. {
  1059. return actualName.empty() ? type : type + "." + actualName;
  1060. }
  1061. else
  1062. {
  1063. return actualName.empty() ? actualScope+ ":" + type : actualScope + ":" + type + "." + actualName;
  1064. }
  1065. }
  1066. VCMI_LIB_NAMESPACE_END