CModHandler.cpp 39 KB

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