IdentifierStorage.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 "../JsonNode.h"
  15. #include "../VCMI_Lib.h"
  16. #include "../constants/StringConstants.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include <vstd/StringUtils.h>
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. CIdentifierStorage::CIdentifierStorage()
  21. {
  22. //TODO: moddable spell schools
  23. for (auto i = 0; i < GameConstants::DEFAULT_SCHOOLS; ++i)
  24. registerObject(ModScope::scopeBuiltin(), "spellSchool", SpellConfig::SCHOOL[i].jsonName, SpellConfig::SCHOOL[i].id);
  25. registerObject(ModScope::scopeBuiltin(), "spellSchool", "any", SpellSchool(ESpellSchool::ANY));
  26. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; ++i)
  27. {
  28. registerObject(ModScope::scopeBuiltin(), "resource", GameConstants::RESOURCE_NAMES[i], i);
  29. }
  30. for(int i=0; i<GameConstants::PRIMARY_SKILLS; ++i)
  31. {
  32. registerObject(ModScope::scopeBuiltin(), "primSkill", NPrimarySkill::names[i], i);
  33. registerObject(ModScope::scopeBuiltin(), "primarySkill", NPrimarySkill::names[i], i);
  34. }
  35. }
  36. void CIdentifierStorage::checkIdentifier(std::string & ID)
  37. {
  38. if (boost::algorithm::ends_with(ID, "."))
  39. logMod->warn("BIG WARNING: identifier %s seems to be broken!", ID);
  40. else
  41. {
  42. size_t pos = 0;
  43. do
  44. {
  45. if (std::tolower(ID[pos]) != ID[pos] ) //Not in camelCase
  46. {
  47. logMod->warn("Warning: identifier %s is not in camelCase!", ID);
  48. ID[pos] = std::tolower(ID[pos]);// Try to fix the ID
  49. }
  50. pos = ID.find('.', pos);
  51. }
  52. while(pos++ != std::string::npos);
  53. }
  54. }
  55. void CIdentifierStorage::requestIdentifier(ObjectCallback callback) const
  56. {
  57. checkIdentifier(callback.type);
  58. checkIdentifier(callback.name);
  59. assert(!callback.localScope.empty());
  60. if (state != ELoadingState::FINISHED) // enqueue request if loading is still in progress
  61. scheduledRequests.push_back(callback);
  62. else // execute immediately for "late" requests
  63. resolveIdentifier(callback);
  64. }
  65. CIdentifierStorage::ObjectCallback CIdentifierStorage::ObjectCallback::fromNameWithType(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback, bool optional)
  66. {
  67. assert(!scope.empty());
  68. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  69. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  70. if (scope == scopeAndFullName.first)
  71. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  72. ObjectCallback result;
  73. result.localScope = scope;
  74. result.remoteScope = scopeAndFullName.first;
  75. result.type = typeAndName.first;
  76. result.name = typeAndName.second;
  77. result.callback = callback;
  78. result.optional = optional;
  79. return result;
  80. }
  81. 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)
  82. {
  83. assert(!scope.empty());
  84. auto scopeAndFullName = vstd::splitStringToPair(fullName, ':');
  85. auto typeAndName = vstd::splitStringToPair(scopeAndFullName.second, '.');
  86. if(!typeAndName.first.empty())
  87. {
  88. if (typeAndName.first != type)
  89. logMod->error("Identifier '%s' from mod '%s' requested with different type! Type '%s' expected!", fullName, scope, type);
  90. else
  91. logMod->debug("Target type for identifier '%s' defined in mod '%s' is redundant!", fullName, scope);
  92. }
  93. if (scope == scopeAndFullName.first)
  94. logMod->debug("Target scope for identifier '%s' is redundant! Identifier already defined in mod '%s'", fullName, scope);
  95. ObjectCallback result;
  96. result.localScope = scope;
  97. result.remoteScope = scopeAndFullName.first;
  98. result.type = type;
  99. result.name = typeAndName.second;
  100. result.callback = callback;
  101. result.optional = optional;
  102. return result;
  103. }
  104. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  105. {
  106. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, false));
  107. }
  108. void CIdentifierStorage::requestIdentifier(const std::string & scope, const std::string & fullName, const std::function<void(si32)> & callback) const
  109. {
  110. requestIdentifier(ObjectCallback::fromNameWithType(scope, fullName, callback, false));
  111. }
  112. void CIdentifierStorage::requestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  113. {
  114. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, false));
  115. }
  116. void CIdentifierStorage::requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback) const
  117. {
  118. requestIdentifier(ObjectCallback::fromNameWithType(name.meta, name.String(), callback, false));
  119. }
  120. void CIdentifierStorage::tryRequestIdentifier(const std::string & scope, const std::string & type, const std::string & name, const std::function<void(si32)> & callback) const
  121. {
  122. requestIdentifier(ObjectCallback::fromNameAndType(scope, type, name, callback, true));
  123. }
  124. void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function<void(si32)> & callback) const
  125. {
  126. requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true));
  127. }
  128. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) const
  129. {
  130. //TODO: RE-ENABLE
  131. //assert(state != ELoadingState::LOADING);
  132. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function<void(si32)>(), silent));
  133. if (idList.size() == 1)
  134. return idList.front().id;
  135. if (!silent)
  136. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope);
  137. return std::optional<si32>();
  138. }
  139. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) const
  140. {
  141. assert(state != ELoadingState::LOADING);
  142. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function<void(si32)>(), silent));
  143. if (idList.size() == 1)
  144. return idList.front().id;
  145. if (!silent)
  146. logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta);
  147. return std::optional<si32>();
  148. }
  149. std::optional<si32> CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) const
  150. {
  151. assert(state != ELoadingState::LOADING);
  152. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function<void(si32)>(), silent));
  153. if (idList.size() == 1)
  154. return idList.front().id;
  155. if (!silent)
  156. logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta);
  157. return std::optional<si32>();
  158. }
  159. std::optional<si32> CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) const
  160. {
  161. assert(state != ELoadingState::LOADING);
  162. auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function<void(si32)>(), silent));
  163. if (idList.size() == 1)
  164. return idList.front().id;
  165. if (!silent)
  166. logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope);
  167. return std::optional<si32>();
  168. }
  169. void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier)
  170. {
  171. assert(state != ELoadingState::FINISHED);
  172. ObjectData data;
  173. data.scope = scope;
  174. data.id = identifier;
  175. std::string fullID = type + '.' + name;
  176. checkIdentifier(fullID);
  177. std::pair<const std::string, ObjectData> mapping = std::make_pair(fullID, data);
  178. if(!vstd::containsMapping(registeredObjects, mapping))
  179. {
  180. logMod->trace("registered %s as %s:%s", fullID, scope, identifier);
  181. registeredObjects.insert(mapping);
  182. }
  183. }
  184. std::vector<CIdentifierStorage::ObjectData> CIdentifierStorage::getPossibleIdentifiers(const ObjectCallback & request) const
  185. {
  186. std::set<std::string> allowedScopes;
  187. bool isValidScope = true;
  188. // called have not specified destination mod explicitly
  189. if (request.remoteScope.empty())
  190. {
  191. // special scope that should have access to all in-game objects
  192. if (request.localScope == ModScope::scopeGame())
  193. {
  194. for(const auto & modName : VLC->modh->getActiveMods())
  195. allowedScopes.insert(modName);
  196. }
  197. // normally ID's from all required mods, own mod and virtual built-in mod are allowed
  198. else if(request.localScope != ModScope::scopeBuiltin() && !request.localScope.empty())
  199. {
  200. allowedScopes = VLC->modh->getModDependencies(request.localScope, isValidScope);
  201. if(!isValidScope)
  202. return std::vector<ObjectData>();
  203. allowedScopes.insert(request.localScope);
  204. }
  205. // all mods can access built-in mod
  206. allowedScopes.insert(ModScope::scopeBuiltin());
  207. }
  208. else
  209. {
  210. //if destination mod was specified explicitly, restrict lookup to this mod
  211. if(request.remoteScope == ModScope::scopeBuiltin() )
  212. {
  213. //built-in mod is an implicit dependency for all mods, allow access into it
  214. allowedScopes.insert(request.remoteScope);
  215. }
  216. else if ( request.localScope == ModScope::scopeGame() )
  217. {
  218. // allow access, this is special scope that should have access to all in-game objects
  219. allowedScopes.insert(request.remoteScope);
  220. }
  221. else if(request.remoteScope == request.localScope )
  222. {
  223. // allow self-access
  224. allowedScopes.insert(request.remoteScope);
  225. }
  226. else
  227. {
  228. // allow access only if mod is in our dependencies
  229. auto myDeps = VLC->modh->getModDependencies(request.localScope, isValidScope);
  230. if(!isValidScope)
  231. return std::vector<ObjectData>();
  232. if(myDeps.count(request.remoteScope))
  233. allowedScopes.insert(request.remoteScope);
  234. }
  235. }
  236. std::string fullID = request.type + '.' + request.name;
  237. auto entries = registeredObjects.equal_range(fullID);
  238. if (entries.first != entries.second)
  239. {
  240. std::vector<ObjectData> locatedIDs;
  241. for (auto it = entries.first; it != entries.second; it++)
  242. {
  243. if (vstd::contains(allowedScopes, it->second.scope))
  244. {
  245. locatedIDs.push_back(it->second);
  246. }
  247. }
  248. return locatedIDs;
  249. }
  250. return std::vector<ObjectData>();
  251. }
  252. bool CIdentifierStorage::resolveIdentifier(const ObjectCallback & request) const
  253. {
  254. auto identifiers = getPossibleIdentifiers(request);
  255. if (identifiers.size() == 1) // normally resolved ID
  256. {
  257. request.callback(identifiers.front().id);
  258. return true;
  259. }
  260. if (request.optional && identifiers.empty()) // failed to resolve optinal ID
  261. {
  262. return true;
  263. }
  264. // error found. Try to generate some debug info
  265. if(identifiers.empty())
  266. logMod->error("Unknown identifier!");
  267. else
  268. logMod->error("Ambiguous identifier request!");
  269. logMod->error("Request for %s.%s from mod %s", request.type, request.name, request.localScope);
  270. for(const auto & id : identifiers)
  271. {
  272. logMod->error("\tID is available in mod %s", id.scope);
  273. }
  274. return false;
  275. }
  276. void CIdentifierStorage::finalize()
  277. {
  278. assert(state == ELoadingState::LOADING);
  279. state = ELoadingState::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 = ELoadingState::FINISHED;
  299. }
  300. VCMI_LIB_NAMESPACE_END