CObjectClassesHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * CObjectClassesHandler.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 "CObjectClassesHandler.h"
  12. #include "../filesystem/Filesystem.h"
  13. #include "../filesystem/CBinaryReader.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../GameConstants.h"
  16. #include "../StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../JsonNode.h"
  21. #include "../CSoundBase.h"
  22. #include "../mapObjectConstructors/CBankInstanceConstructor.h"
  23. #include "../mapObjectConstructors/CRewardableConstructor.h"
  24. #include "../mapObjectConstructors/CommonConstructors.h"
  25. #include "../mapObjectConstructors/HillFortInstanceConstructor.h"
  26. #include "../mapObjectConstructors/ShipyardInstanceConstructor.h"
  27. #include "../mapObjectConstructors/ShrineInstanceConstructor.h"
  28. #include "../mapObjects/CGPandoraBox.h"
  29. #include "../mapObjects/CQuest.h"
  30. #include "../mapObjects/ObjectTemplate.h"
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. CObjectClassesHandler::CObjectClassesHandler()
  33. {
  34. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  35. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME>>
  36. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  37. //Note: should be in sync with registerTypesMapObjectTypes function
  38. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  39. SET_HANDLER_CLASS("dwelling", CDwellingInstanceConstructor);
  40. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  41. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  42. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  43. SET_HANDLER_CLASS("boat", BoatInstanceConstructor);
  44. SET_HANDLER_CLASS("market", MarketInstanceConstructor);
  45. SET_HANDLER_CLASS("shrine", ShrineInstanceConstructor);
  46. SET_HANDLER_CLASS("hillFort", HillFortInstanceConstructor);
  47. SET_HANDLER_CLASS("shipyard", ShipyardInstanceConstructor);
  48. SET_HANDLER_CLASS("static", CObstacleConstructor);
  49. SET_HANDLER_CLASS("", CObstacleConstructor);
  50. SET_HANDLER("randomArtifact", CGArtifact);
  51. SET_HANDLER("randomHero", CGHeroInstance);
  52. SET_HANDLER("randomResource", CGResource);
  53. SET_HANDLER("randomTown", CGTownInstance);
  54. SET_HANDLER("randomMonster", CGCreature);
  55. SET_HANDLER("randomDwelling", CGDwelling);
  56. SET_HANDLER("generic", CGObjectInstance);
  57. SET_HANDLER("cartographer", CCartographer);
  58. SET_HANDLER("artifact", CGArtifact);
  59. SET_HANDLER("borderGate", CGBorderGate);
  60. SET_HANDLER("borderGuard", CGBorderGuard);
  61. SET_HANDLER("monster", CGCreature);
  62. SET_HANDLER("denOfThieves", CGDenOfthieves);
  63. SET_HANDLER("event", CGEvent);
  64. SET_HANDLER("garrison", CGGarrison);
  65. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  66. SET_HANDLER("keymaster", CGKeymasterTent);
  67. SET_HANDLER("lighthouse", CGLighthouse);
  68. SET_HANDLER("magi", CGMagi);
  69. SET_HANDLER("mine", CGMine);
  70. SET_HANDLER("obelisk", CGObelisk);
  71. SET_HANDLER("observatory", CGObservatory);
  72. SET_HANDLER("pandora", CGPandoraBox);
  73. SET_HANDLER("prison", CGHeroInstance);
  74. SET_HANDLER("questGuard", CGQuestGuard);
  75. SET_HANDLER("resource", CGResource);
  76. SET_HANDLER("scholar", CGScholar);
  77. SET_HANDLER("seerHut", CGSeerHut);
  78. SET_HANDLER("sign", CGSignBottle);
  79. SET_HANDLER("siren", CGSirens);
  80. SET_HANDLER("monolith", CGMonolith);
  81. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  82. SET_HANDLER("whirlpool", CGWhirlpool);
  83. SET_HANDLER("witch", CGWitchHut);
  84. SET_HANDLER("terrain", CGTerrainPatch);
  85. #undef SET_HANDLER_CLASS
  86. #undef SET_HANDLER
  87. }
  88. CObjectClassesHandler::~CObjectClassesHandler()
  89. {
  90. for(auto * p : objects)
  91. delete p;
  92. }
  93. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData()
  94. {
  95. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_OBJECT);
  96. CLegacyConfigParser parser("Data/Objects.txt");
  97. auto totalNumber = static_cast<size_t>(parser.readNumber()); // first line contains number of objects to read and nothing else
  98. parser.endLine();
  99. for (size_t i = 0; i < totalNumber; i++)
  100. {
  101. auto * tmpl = new ObjectTemplate;
  102. tmpl->readTxt(parser);
  103. parser.endLine();
  104. std::pair<si32, si32> key(tmpl->id.num, tmpl->subid);
  105. legacyTemplates.insert(std::make_pair(key, std::shared_ptr<const ObjectTemplate>(tmpl)));
  106. }
  107. objects.resize(256);
  108. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  109. assert(dataSize == 256);
  110. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  111. for (size_t i=0; i<256; i++)
  112. {
  113. ret[i]["name"].String() = namesParser.readString();
  114. namesParser.endLine();
  115. }
  116. JsonNode cregen1;
  117. JsonNode cregen4;
  118. CLegacyConfigParser cregen1Parser("data/crgen1");
  119. do
  120. {
  121. JsonNode subObject;
  122. subObject["name"].String() = cregen1Parser.readString();
  123. cregen1.Vector().push_back(subObject);
  124. }
  125. while(cregen1Parser.endLine());
  126. CLegacyConfigParser cregen4Parser("data/crgen4");
  127. do
  128. {
  129. JsonNode subObject;
  130. subObject["name"].String() = cregen4Parser.readString();
  131. cregen4.Vector().push_back(subObject);
  132. }
  133. while(cregen4Parser.endLine());
  134. ret[Obj::CREATURE_GENERATOR1]["subObjects"] = cregen1;
  135. ret[Obj::CREATURE_GENERATOR4]["subObjects"] = cregen4;
  136. ret[Obj::REFUGEE_CAMP]["subObjects"].Vector().push_back(ret[Obj::REFUGEE_CAMP]);
  137. ret[Obj::WAR_MACHINE_FACTORY]["subObjects"].Vector().push_back(ret[Obj::WAR_MACHINE_FACTORY]);
  138. return ret;
  139. }
  140. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj)
  141. {
  142. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, obj->objects.size());
  143. assert(object);
  144. obj->objects.push_back(object);
  145. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  146. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  147. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  148. }
  149. void CObjectClassesHandler::loadSubObject(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  150. {
  151. auto object = loadSubObjectFromJson(scope, identifier, entry, obj, index);
  152. assert(object);
  153. assert(obj->objects[index] == nullptr); // ensure that this id was not loaded before
  154. obj->objects[index] = object;
  155. registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype);
  156. for(const auto & compatID : entry["compatibilityIdentifiers"].Vector())
  157. registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype);
  158. }
  159. TObjectTypeHandler CObjectClassesHandler::loadSubObjectFromJson(const std::string & scope, const std::string & identifier, const JsonNode & entry, ObjectClass * obj, size_t index)
  160. {
  161. assert(identifier.find(':') == std::string::npos);
  162. assert(!scope.empty());
  163. if(!handlerConstructors.count(obj->handlerName))
  164. {
  165. logGlobal->error("Handler with name %s was not found!", obj->handlerName);
  166. return nullptr;
  167. }
  168. auto createdObject = handlerConstructors.at(obj->handlerName)();
  169. createdObject->modScope = scope;
  170. createdObject->typeName = obj->identifier;;
  171. createdObject->subTypeName = identifier;
  172. createdObject->type = obj->id;
  173. createdObject->subtype = index;
  174. createdObject->init(entry);
  175. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, index));
  176. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  177. {
  178. createdObject->addTemplate(templ.second);
  179. }
  180. legacyTemplates.erase(range.first, range.second);
  181. logGlobal->debug("Loaded object %s(%d)::%s(%d)", obj->getJsonKey(), obj->id, identifier, index);
  182. return createdObject;
  183. }
  184. std::string ObjectClass::getJsonKey() const
  185. {
  186. return modScope + ':' + identifier;
  187. }
  188. std::string ObjectClass::getNameTextID() const
  189. {
  190. return TextIdentifier("object", modScope, identifier, "name").get();
  191. }
  192. std::string ObjectClass::getNameTranslated() const
  193. {
  194. return VLC->generaltexth->translate(getNameTextID());
  195. }
  196. ObjectClass * CObjectClassesHandler::loadFromJson(const std::string & scope, const JsonNode & json, const std::string & name, size_t index)
  197. {
  198. auto * obj = new ObjectClass();
  199. obj->modScope = scope;
  200. obj->identifier = name;
  201. obj->handlerName = json["handler"].String();
  202. obj->base = json["base"];
  203. obj->id = index;
  204. VLC->generaltexth->registerString(scope, obj->getNameTextID(), json["name"].String());
  205. obj->objects.resize(json["lastReservedIndex"].Float() + 1);
  206. for (auto subData : json["types"].Struct())
  207. {
  208. if (!subData.second["index"].isNull())
  209. {
  210. const std::string & subMeta = subData.second["index"].meta;
  211. if ( subMeta != "core")
  212. logMod->warn("Object %s:%s.%s - attempt to load object with preset index! This option is reserved for built-in mod", subMeta, name, subData.first );
  213. size_t subIndex = subData.second["index"].Integer();
  214. loadSubObject(subData.second.meta, subData.first, subData.second, obj, subIndex);
  215. }
  216. else
  217. loadSubObject(subData.second.meta, subData.first, subData.second, obj);
  218. }
  219. return obj;
  220. }
  221. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  222. {
  223. auto * object = loadFromJson(scope, data, name, objects.size());
  224. objects.push_back(object);
  225. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  226. }
  227. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  228. {
  229. auto * object = loadFromJson(scope, data, name, index);
  230. assert(objects[(si32)index] == nullptr); // ensure that this id was not loaded before
  231. objects[static_cast<si32>(index)] = object;
  232. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  233. }
  234. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, si32 ID, si32 subID)
  235. {
  236. config.setType(JsonNode::JsonType::DATA_STRUCT); // ensure that input is not NULL
  237. assert(ID < objects.size());
  238. assert(objects[ID]);
  239. if ( subID >= objects[ID]->objects.size())
  240. objects[ID]->objects.resize(subID+1);
  241. JsonUtils::inherit(config, objects.at(ID)->base);
  242. loadSubObject(config.meta, identifier, config, objects[ID], subID);
  243. }
  244. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  245. {
  246. assert(ID < objects.size());
  247. assert(objects[ID]);
  248. assert(subID < objects[ID]->objects.size());
  249. objects[ID]->objects[subID] = nullptr;
  250. }
  251. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  252. {
  253. return std::vector<bool>(); //TODO?
  254. }
  255. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  256. {
  257. assert(type < objects.size());
  258. assert(objects[type]);
  259. assert(subtype < objects[type]->objects.size());
  260. return objects.at(type)->objects.at(subtype);
  261. }
  262. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const
  263. {
  264. std::optional<si32> id = VLC->modh->identifiers.getIdentifier(scope, "object", type);
  265. if(id)
  266. {
  267. auto * object = objects[id.value()];
  268. std::optional<si32> subID = VLC->modh->identifiers.getIdentifier(scope, object->getJsonKey(), subtype);
  269. if (subID)
  270. return object->objects[subID.value()];
  271. }
  272. std::string errorString = "Failed to find object of type " + type + "::" + subtype;
  273. logGlobal->error(errorString);
  274. throw std::runtime_error(errorString);
  275. }
  276. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(CompoundMapObjectID compoundIdentifier) const
  277. {
  278. return getHandlerFor(compoundIdentifier.primaryID, compoundIdentifier.secondaryID);
  279. }
  280. std::set<si32> CObjectClassesHandler::knownObjects() const
  281. {
  282. std::set<si32> ret;
  283. for(auto * entry : objects)
  284. if (entry)
  285. ret.insert(entry->id);
  286. return ret;
  287. }
  288. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  289. {
  290. std::set<si32> ret;
  291. if (!objects.at(primaryID))
  292. {
  293. logGlobal->error("Failed to find object %d", primaryID);
  294. return ret;
  295. }
  296. for(const auto & entry : objects.at(primaryID)->objects)
  297. if (entry)
  298. ret.insert(entry->subtype);
  299. return ret;
  300. }
  301. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  302. {
  303. for (auto & entry : object["types"].Struct())
  304. {
  305. if (object.Struct().count("subObjects"))
  306. {
  307. const auto & vector = object["subObjects"].Vector();
  308. if (entry.second.Struct().count("index"))
  309. {
  310. size_t index = entry.second["index"].Integer();
  311. if (index < vector.size())
  312. JsonUtils::inherit(entry.second, vector[index]);
  313. }
  314. }
  315. JsonUtils::inherit(entry.second, object["base"]);
  316. for (auto & templ : entry.second["templates"].Struct())
  317. JsonUtils::inherit(templ.second, entry.second["base"]);
  318. }
  319. object.Struct().erase("subObjects");
  320. }
  321. void CObjectClassesHandler::afterLoadFinalization()
  322. {
  323. for(auto * entry : objects)
  324. {
  325. if (!entry)
  326. continue;
  327. for(const auto & obj : entry->objects)
  328. {
  329. if (!obj)
  330. continue;
  331. obj->afterLoadFinalization();
  332. if(obj->getTemplates().empty())
  333. logGlobal->warn("No templates found for %s:%s", entry->getJsonKey(), obj->getJsonKey());
  334. }
  335. }
  336. generateExtraMonolithsForRMG();
  337. }
  338. void CObjectClassesHandler::generateExtraMonolithsForRMG()
  339. {
  340. //duplicate existing two-way portals to make reserve for RMG
  341. auto& portalVec = objects[Obj::MONOLITH_TWO_WAY]->objects;
  342. //FIXME: Monoliths in this vector can be already not useful for every terrain
  343. const size_t portalCount = portalVec.size();
  344. //Invalid portals will be skipped and portalVec size stays unchanged
  345. for (size_t i = portalCount; portalVec.size() < 100; ++i)
  346. {
  347. auto index = static_cast<si32>(i % portalCount);
  348. auto portal = portalVec[index];
  349. auto templates = portal->getTemplates();
  350. if (templates.empty() || !templates[0]->canBePlacedAtAnyTerrain())
  351. {
  352. continue; //Do not clone HoTA water-only portals or any others we can't use
  353. }
  354. //deep copy of noncopyable object :?
  355. auto newPortal = std::make_shared<CDefaultObjectTypeHandler<CGMonolith>>();
  356. newPortal->rmgInfo = portal->getRMGInfo();
  357. newPortal->base = portal->base; //not needed?
  358. newPortal->templates = portal->getTemplates();
  359. newPortal->sounds = portal->getSounds();
  360. newPortal->aiValue = portal->getAiValue();
  361. newPortal->battlefield = portal->battlefield; //getter is not initialized at this point
  362. newPortal->modScope = portal->modScope; //private
  363. newPortal->typeName = portal->getTypeName();
  364. newPortal->subTypeName = std::string("monolith") + std::to_string(portalVec.size());
  365. newPortal->type = portal->getIndex();
  366. newPortal->subtype = portalVec.size(); //indexes must be unique, they are returned as a set
  367. portalVec.push_back(newPortal);
  368. }
  369. }
  370. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  371. {
  372. const auto handler = getHandlerFor(type, subtype);
  373. if (handler && handler->hasNameTextID())
  374. return handler->getNameTranslated();
  375. else
  376. return objects[type]->getNameTranslated();
  377. }
  378. SObjectSounds CObjectClassesHandler::getObjectSounds(si32 type, si32 subtype) const
  379. {
  380. // TODO: these objects may have subID's that does not have associated handler:
  381. // Prison: uses hero type as subID
  382. // Hero: uses hero type as subID, but registers hero classes as subtypes
  383. // Spell scroll: uses spell ID as subID
  384. if(type == Obj::PRISON || type == Obj::HERO || type == Obj::SPELL_SCROLL)
  385. subtype = 0;
  386. assert(type < objects.size());
  387. assert(objects[type]);
  388. assert(subtype < objects[type]->objects.size());
  389. return getHandlerFor(type, subtype)->getSounds();
  390. }
  391. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  392. {
  393. return objects.at(type)->handlerName;
  394. }
  395. VCMI_LIB_NAMESPACE_END