IdentifierStorage.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * IdentifierStorage.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 "IdentifierStorage.h"
  12. #include "CModHandler.h"
  13. #include "ModScope.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../constants/StringConstants.h"
  16. #include "../spells/CSpellHandler.h"
  17. #include <vstd/StringUtils.h>
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. CIdentifierStorage::CIdentifierStorage()
  20. {
  21. //TODO: moddable spell schools
  22. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  23. registerObject(ModScope::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id.getNum());
  24. registerObject(ModScope::scopeBuiltin(), "spellSchool", "any", SpellSchool::ANY.getNum());
  25. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  26. registerObject(ModScope::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  27. for (int i = 0; i < std::size(GameConstants::PLAYER_COLOR_NAMES); ++i)
  28. registerObject(ModScope::scopeBuiltin(), "playerColor", GameConstants::PLAYER_COLOR_NAMES[i], i);
  29. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  30. {
  31. registerObject(ModScope::scopeBuiltin(), "primSkill", NPrimarySkill::names[i], i);
  32. registerObject(ModScope::scopeBuiltin(), "primarySkill", NPrimarySkill::names[i], i);
  33. }
  34. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageBoth", 0);
  35. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMin", 1);
  36. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureDamageMax", 2);
  37. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeAll", -1);
  38. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeMelee", 0);
  39. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "damageTypeRanged", 1);
  40. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementLand", 1);
  41. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "heroMovementSea", 0);
  42. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareGorgon", 0);
  43. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareCommander", 1);
  44. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareNoRangePenalty", 2);
  45. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareRangePenalty", 3);
  46. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareObstaclePenalty", 4);
  47. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "deathStareRangeObstaclePenalty", 5);
  48. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthRegular", 0);
  49. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "rebirthSpecial", 1);
  50. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsMonsters", 0);
  51. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsHeroes", 1);
  52. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "visionsTowns", 2);
  53. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityBattleWide", 0);
  54. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "immunityEnemyHero", 1);
  55. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerHealth", 0);
  56. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "transmutationPerUnit", 1);
  57. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillPercentage", 0);
  58. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "destructionKillAmount", 1);
  59. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealPermanent", 0);
  60. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "soulStealBattle", 1);
  61. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementFlying", 0);
  62. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "movementTeleporting", 1);
  63. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel1", 1);
  64. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel2", 2);
  65. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel3", 3);
  66. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel4", 4);
  67. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "spellLevel5", 5);
  68. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel1", 1);
  69. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel2", 2);
  70. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel3", 3);
  71. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel4", 4);
  72. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel5", 5);
  73. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel6", 6);
  74. registerObject(ModScope::scopeBuiltin(), "bonusSubtype", "creatureLevel7", 7);
  75. registerObject(ModScope::scopeBuiltin(), "spell", "preset", SpellID::PRESET);
  76. registerObject(ModScope::scopeBuiltin(), "spell", "spellbook_preset", SpellID::SPELLBOOK_PRESET);
  77. }
  78. void CIdentifierStorage::checkIdentifier(std::string & ID)
  79. {
  80. if (boost::algorithm::ends_with(ID, "."))
  81. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  82. else
  83. {
  84. size_t pos = 0;
  85. do
  86. {
  87. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  88. {
  89. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  90. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  91. }
  92. pos = ID.find('.', pos);
  93. }
  94. while(pos++ != std::string::npos);
  95. }
  96. }
  97. void CIdentifierStorage::requestIdentifier(ObjectCallback callback) const
  98. {
  99. checkIdentifier(callback.type);
  100. checkIdentifier(callback.name);
  101. assert(!callback.localScope.empty());
  102. if (state != ELoadingState::FINISHED) // enqueue request if loading is still in progress
  103. scheduledRequests.push_back(callback);
  104. else // execute immediately for "late" requests
  105. resolveIdentifier(callback);
  106. }
  107. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  108. {
  109. assert(!scope.empty());
  110. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  111. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  112. if (scope == scopeAndFullName.first)
  113. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  114. ObjectCallback result;
  115. result.localScope = scope;
  116. result.remoteScope = scopeAndFullName.first;
  117. result.type = typeAndName.first;
  118. result.name = typeAndName.second;
  119. result.callback = callback;
  120. result.optional = optional;
  121. result.dynamicType = true;
  122. return result;
  123. }
  124. 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)
  125. {
  126. assert(!scope.empty());
  127. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  128. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  129. if(!typeAndName.first.empty())
  130. {
  131. if (typeAndName.first != type)
  132. logMod->warn("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  133. else
  134. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  135. }
  136. if (scope == scopeAndFullName.first)
  137. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  138. ObjectCallback result;
  139. result.localScope = scope;
  140. result.remoteScope = scopeAndFullName.first;
  141. result.type = type;
  142. result.name = typeAndName.second;
  143. result.callback = callback;
  144. result.optional = optional;
  145. result.dynamicType = false;
  146. return result;
  147. }
  148. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  149. {
  150. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  151. }
  152. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback) const
  153. {
  154. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  155. }
  156. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  157. {
  158. requestIdentifier(ObjectCallback::fromNameAndType(name.getModScope(), type, name.String(), callback, false));
  159. }
  160. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback) const
  161. {
  162. requestIdentifier(ObjectCallback::fromNameWithType(name.getModScope(), name.String(), callback, false));
  163. }
  164. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  165. {
  166. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  167. }
  168. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  169. {
  170. requestIdentifier(ObjectCallback::fromNameAndType(name.getModScope(), type, name.String(), callback, true));
  171. }
  172. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) const
  173. {
  174. //assert(state != ELoadingState::LOADING);
  175. auto options = ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent);
  176. return getIdentifierImpl(options, silent);
  177. }
  178. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) const
  179. {
  180. assert(state != ELoadingState::LOADING);
  181. auto options = ObjectCallback::fromNameAndType(name.getModScope(), type, name.String(), std::function<void(si32)>(), silent);
  182. return getIdentifierImpl(options, silent);
  183. }
  184. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) const
  185. {
  186. assert(state != ELoadingState::LOADING);
  187. auto options = ObjectCallback::fromNameWithType(name.getModScope(), name.String(), std::function<void(si32)>(), silent);
  188. return getIdentifierImpl(options, silent);
  189. }
  190. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) const
  191. {
  192. assert(state != ELoadingState::LOADING);
  193. auto options = ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent);
  194. return getIdentifierImpl(options, silent);
  195. }
  196. std::optional<si32> CIdentifierStorage::getIdentifierImpl(const ObjectCallback & options, bool silent) const
  197. {
  198. auto idList = getPossibleIdentifiers(options);
  199. if (idList.size() == 1)
  200. return idList.front().id;
  201. if (!silent)
  202. showIdentifierResolutionErrorDetails(options);
  203. return std::optional<si32>();
  204. }
  205. void CIdentifierStorage::showIdentifierResolutionErrorDetails(const ObjectCallback & options) const
  206. {
  207. auto idList = getPossibleIdentifiers(options);
  208. logMod->error("Failed to resolve identifier '%s' of type '%s' from mod '%s'", options.name, options.type, options.localScope);
  209. if (options.dynamicType && options.type.empty())
  210. {
  211. bool suggestionFound = false;
  212. for (auto const & entry : registeredObjects)
  213. {
  214. if (!boost::algorithm::ends_with(entry.first, options.name))
  215. continue;
  216. suggestionFound = true;
  217. logMod->error("Perhaps you wanted to use identifier '%s' from mod '%s' instead?", entry.first, entry.second.scope);
  218. }
  219. if (suggestionFound)
  220. return;
  221. }
  222. if (idList.empty())
  223. {
  224. // check whether identifier is unavailable due to a missing dependency on a mod
  225. ObjectCallback testOptions = options;
  226. testOptions.localScope = ModScope::scopeGame();
  227. testOptions.remoteScope = {};
  228. auto testList = getPossibleIdentifiers(testOptions);
  229. if (testList.empty())
  230. {
  231. logMod->error("Identifier '%s' of type '%s' does not exists in any loaded mod!", options.name, options.type);
  232. }
  233. else
  234. {
  235. // such identifiers exists, but were not picked for some reason
  236. if (options.remoteScope.empty())
  237. {
  238. // attempt to access identifier from mods that is not dependency
  239. for (auto const & testOption : testList)
  240. {
  241. logMod->error("Identifier '%s' exists in mod %s", options.name, testOption.scope);
  242. logMod->error("Please add mod '%s' as dependency of mod '%s' to access this identifier", testOption.scope, options.localScope);
  243. }
  244. }
  245. else
  246. {
  247. // attempt to access identifier in form 'modName:object', but identifier is only present in different mod
  248. for (auto const & testOption : testList)
  249. {
  250. logMod->error("Identifier '%s' exists in mod '%s' but identifier was explicitly requested from mod '%s'!", options.name, testOption.scope, options.remoteScope);
  251. if (options.dynamicType)
  252. logMod->error("Please use form '%s.%s' or '%s:%s.%s' to access this identifier", options.type, options.name, testOption.scope, options.type, options.name);
  253. else
  254. logMod->error("Please use form '%s' or '%s:%s' to access this identifier", options.name, testOption.scope, options.name);
  255. }
  256. }
  257. }
  258. }
  259. else
  260. {
  261. logMod->error("Multiple possible candidates:");
  262. for (auto const & testOption : idList)
  263. {
  264. logMod->error("Identifier %s exists in mod %s", options.name, testOption.scope);
  265. if (options.dynamicType)
  266. logMod->error("Please use '%s:%s.%s' to access this identifier", testOption.scope, options.type, options.name);
  267. else
  268. logMod->error("Please use '%s:%s' to access this identifier", testOption.scope, options.name);
  269. }
  270. }
  271. }
  272. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  273. {
  274. assert(state != ELoadingState::FINISHED);
  275. ObjectData data;
  276. data.scope = scope;
  277. data.id = identifier;
  278. std::string fullID = type + '.' + name;
  279. checkIdentifier(fullID);
  280. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  281. if(!vstd::containsMapping(registeredObjects, mapping))
  282. {
  283. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  284. registeredObjects.insert(mapping);
  285. }
  286. }
  287. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request) const
  288. {
  289. std::set<std::string> allowedScopes;
  290. bool isValidScope = true;
  291. // called have not specified destination mod explicitly
  292. if (request.remoteScope.empty())
  293. {
  294. // special scope that should have access to all in-game objects
  295. if (request.localScope == ModScope::scopeGame())
  296. {
  297. for(const auto & modName : VLC->modh->getActiveMods())
  298. allowedScopes.insert(modName);
  299. }
  300. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  301. else if(request.localScope != ModScope::scopeBuiltin() && !request.localScope.empty())
  302. {
  303. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  304. if(!isValidScope)
  305. return std::vector<ObjectData>();
  306. allowedScopes.insert(request.localScope);
  307. }
  308. // all mods can access built-in mod
  309. allowedScopes.insert(ModScope::scopeBuiltin());
  310. }
  311. else
  312. {
  313. //if destination mod was specified explicitly, restrict lookup to this mod
  314. if(request.remoteScope == ModScope::scopeBuiltin() )
  315. {
  316. //built-in mod is an implicit dependency for all mods, allow access into it
  317. allowedScopes.insert(request.remoteScope);
  318. }
  319. else if ( request.localScope == ModScope::scopeGame() )
  320. {
  321. // allow access, this is special scope that should have access to all in-game objects
  322. allowedScopes.insert(request.remoteScope);
  323. }
  324. else if(request.remoteScope == request.localScope )
  325. {
  326. // allow self-access
  327. allowedScopes.insert(request.remoteScope);
  328. }
  329. else
  330. {
  331. // allow access only if mod is in our dependencies
  332. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  333. if(!isValidScope)
  334. return std::vector<ObjectData>();
  335. if(myDeps.count(request.remoteScope))
  336. allowedScopes.insert(request.remoteScope);
  337. }
  338. }
  339. std::string fullID = request.type + '.' + request.name;
  340. auto entries = registeredObjects.equal_range(fullID);
  341. if (entries.first != entries.second)
  342. {
  343. std::vector<ObjectData> locatedIDs;
  344. for (auto it = entries.first; it != entries.second; it++)
  345. {
  346. if (vstd::contains(allowedScopes, it->second.scope))
  347. {
  348. locatedIDs.push_back(it->second);
  349. }
  350. }
  351. return locatedIDs;
  352. }
  353. return std::vector<ObjectData>();
  354. }
  355. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request) const
  356. {
  357. auto identifiers = getPossibleIdentifiers(request);
  358. if (identifiers.size() == 1) // normally resolved ID
  359. {
  360. request.callback(identifiers.front().id);
  361. return true;
  362. }
  363. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  364. {
  365. return true;
  366. }
  367. // error found. Try to generate some debug info
  368. showIdentifierResolutionErrorDetails(request);
  369. return false;
  370. }
  371. void CIdentifierStorage::finalize()
  372. {
  373. assert(state == ELoadingState::LOADING);
  374. state = ELoadingState::FINALIZING;
  375. while ( !scheduledRequests.empty() )
  376. {
  377. // Use local copy since new requests may appear during resolving, invalidating any iterators
  378. auto request = scheduledRequests.back();
  379. scheduledRequests.pop_back();
  380. resolveIdentifier(request);
  381. }
  382. state = ELoadingState::FINISHED;
  383. }
  384. void CIdentifierStorage::debugDumpIdentifiers()
  385. {
  386. logMod->trace("List of all registered objects:");
  387. std::map<std::string, std::vector<std::string>> objectList;
  388. for(const auto & object : registeredObjects)
  389. {
  390. size_t categoryLength = object.first.find('.');
  391. assert(categoryLength != std::string::npos);
  392. std::string objectCategory = object.first.substr(0, categoryLength);
  393. std::string objectName = object.first.substr(categoryLength + 1);
  394. objectList[objectCategory].push_back("[" + object.second.scope + "] " + objectName);
  395. }
  396. for(auto & category : objectList)
  397. boost::range::sort(category.second);
  398. for(const auto & category : objectList)
  399. {
  400. logMod->trace("");
  401. logMod->trace("### %s", category.first);
  402. logMod->trace("");
  403. for(const auto & entry : category.second)
  404. logMod->trace("- " + entry);
  405. }
  406. }
  407. VCMI_LIB_NAMESPACE_END