CObjectClassesHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #include "StdInc.h"
  2. #include "CObjectClassesHandler.h"
  3. #include "../filesystem/Filesystem.h"
  4. #include "../filesystem/CBinaryReader.h"
  5. #include "../VCMI_Lib.h"
  6. #include "../GameConstants.h"
  7. #include "../StringConstants.h"
  8. #include "../CGeneralTextHandler.h"
  9. #include "../CModHandler.h"
  10. #include "../JsonNode.h"
  11. #include "CRewardableConstructor.h"
  12. #include "CommonConstructors.h"
  13. #include "MapObjects.h"
  14. /*
  15. * CObjectClassesHandler.cpp, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. CObjectClassesHandler::CObjectClassesHandler()
  24. {
  25. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  26. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME> >
  27. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  28. //Note: should be in sync with registerTypesMapObjectTypes function
  29. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  30. SET_HANDLER_CLASS("dwelling", CDwellingInstanceConstructor);
  31. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  32. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  33. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  34. SET_HANDLER_CLASS("static", CObstacleConstructor);
  35. SET_HANDLER_CLASS("", CObstacleConstructor);
  36. SET_HANDLER("randomArtifact", CGArtifact);
  37. SET_HANDLER("randomHero", CGHeroInstance);
  38. SET_HANDLER("randomResource", CGResource);
  39. SET_HANDLER("randomTown", CGTownInstance);
  40. SET_HANDLER("randomMonster", CGCreature);
  41. SET_HANDLER("randomDwelling", CGDwelling);
  42. SET_HANDLER("generic", CGObjectInstance);
  43. SET_HANDLER("market", CGMarket);
  44. SET_HANDLER("cartographer", CCartographer);
  45. SET_HANDLER("artifact", CGArtifact);
  46. SET_HANDLER("blackMarket", CGBlackMarket);
  47. SET_HANDLER("boat", CGBoat);
  48. SET_HANDLER("bonusingObject", CGBonusingObject);
  49. SET_HANDLER("borderGate", CGBorderGate);
  50. SET_HANDLER("borderGuard", CGBorderGuard);
  51. SET_HANDLER("monster", CGCreature);
  52. SET_HANDLER("denOfThieves", CGDenOfthieves);
  53. SET_HANDLER("event", CGEvent);
  54. SET_HANDLER("garrison", CGGarrison);
  55. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  56. SET_HANDLER("keymaster", CGKeymasterTent);
  57. SET_HANDLER("lighthouse", CGLighthouse);
  58. SET_HANDLER("magi", CGMagi);
  59. SET_HANDLER("magicSpring", CGMagicSpring);
  60. SET_HANDLER("magicWell", CGMagicWell);
  61. SET_HANDLER("market", CGMarket);
  62. SET_HANDLER("mine", CGMine);
  63. SET_HANDLER("obelisk", CGObelisk);
  64. SET_HANDLER("observatory", CGObservatory);
  65. SET_HANDLER("onceVisitable", CGOnceVisitable);
  66. SET_HANDLER("pandora", CGPandoraBox);
  67. SET_HANDLER("pickable", CGPickable);
  68. SET_HANDLER("prison", CGHeroInstance);
  69. SET_HANDLER("questGuard", CGQuestGuard);
  70. SET_HANDLER("resource", CGResource);
  71. SET_HANDLER("scholar", CGScholar);
  72. SET_HANDLER("seerHut", CGSeerHut);
  73. SET_HANDLER("shipyard", CGShipyard);
  74. SET_HANDLER("shrine", CGShrine);
  75. SET_HANDLER("sign", CGSignBottle);
  76. SET_HANDLER("siren", CGSirens);
  77. SET_HANDLER("monolith", CGMonolith);
  78. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  79. SET_HANDLER("whirlpool", CGWhirlpool);
  80. SET_HANDLER("university", CGUniversity);
  81. SET_HANDLER("oncePerHero", CGVisitableOPH);
  82. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  83. SET_HANDLER("witch", CGWitchHut);
  84. #undef SET_HANDLER_CLASS
  85. #undef SET_HANDLER
  86. }
  87. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  88. {
  89. CLegacyConfigParser parser("Data/Objects.txt");
  90. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  91. parser.endLine();
  92. for (size_t i=0; i<totalNumber; i++)
  93. {
  94. ObjectTemplate templ;
  95. templ.readTxt(parser);
  96. parser.endLine();
  97. std::pair<si32, si32> key(templ.id.num, templ.subid);
  98. legacyTemplates.insert(std::make_pair(key, templ));
  99. }
  100. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  101. assert(dataSize == 256);
  102. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  103. for (size_t i=0; i<256; i++)
  104. {
  105. ret[i]["name"].String() = namesParser.readString();
  106. namesParser.endLine();
  107. }
  108. CLegacyConfigParser cregen1Parser("data/crgen1");
  109. do
  110. customNames[Obj::CREATURE_GENERATOR1].push_back(cregen1Parser.readString());
  111. while(cregen1Parser.endLine());
  112. CLegacyConfigParser cregen4Parser("data/crgen4");
  113. do
  114. customNames[Obj::CREATURE_GENERATOR4].push_back(cregen4Parser.readString());
  115. while(cregen4Parser.endLine());
  116. return ret;
  117. }
  118. /// selects preferred ID (or subID) for new object
  119. template<typename Map>
  120. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  121. {
  122. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  123. return fixedID.Float(); // H3M object with fixed ID
  124. if (map.empty())
  125. return defaultID; // no objects loaded, keep gap for H3M objects
  126. if (map.rbegin()->first >= defaultID)
  127. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  128. return defaultID; // some H3M objects loaded, first modded found
  129. }
  130. void CObjectClassesHandler::loadObjectEntry(const std::string & identifier, const JsonNode & entry, ObjectContainter * obj)
  131. {
  132. if (!handlerConstructors.count(obj->handlerName))
  133. {
  134. logGlobal->errorStream() << "Handler with name " << obj->handlerName << " was not found!";
  135. return;
  136. }
  137. std::string convertedId = VLC->modh->normalizeIdentifier(entry.meta, "core", identifier);
  138. si32 id = selectNextID(entry["index"], obj->subObjects, 1000);
  139. auto handler = handlerConstructors.at(obj->handlerName)();
  140. handler->setType(obj->id, id);
  141. handler->setTypeName(obj->identifier, convertedId);
  142. if (customNames.count(obj->id) && customNames.at(obj->id).size() > id)
  143. handler->init(entry, customNames.at(obj->id).at(id));
  144. else
  145. handler->init(entry);
  146. if (handler->getTemplates().empty())
  147. {
  148. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, id));
  149. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  150. {
  151. handler->addTemplate(templ.second);
  152. }
  153. legacyTemplates.erase(range.first, range.second);
  154. }
  155. logGlobal->debugStream() << "Loaded object " << obj->identifier << "(" << obj->id << ")" << ":" << convertedId << "(" << id << ")" ;
  156. assert(!obj->subObjects.count(id)); // DO NOT override
  157. obj->subObjects[id] = handler;
  158. obj->subIds[convertedId] = id;
  159. }
  160. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json, const std::string & name)
  161. {
  162. auto obj = new ObjectContainter();
  163. obj->identifier = name;
  164. obj->name = json["name"].String();
  165. obj->handlerName = json["handler"].String();
  166. obj->base = json["base"];
  167. obj->id = selectNextID(json["index"], objects, 256);
  168. for (auto entry : json["types"].Struct())
  169. {
  170. loadObjectEntry(entry.first, entry.second, obj);
  171. }
  172. return obj;
  173. }
  174. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  175. {
  176. auto object = loadFromJson(data, name);
  177. objects[object->id] = object;
  178. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  179. }
  180. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  181. {
  182. auto object = loadFromJson(data, name);
  183. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  184. objects[index] = object;
  185. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  186. }
  187. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, si32 ID, boost::optional<si32> subID)
  188. {
  189. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not NULL
  190. assert(objects.count(ID));
  191. if (subID)
  192. {
  193. assert(objects.at(ID)->subObjects.count(subID.get()) == 0);
  194. assert(config["index"].isNull());
  195. config["index"].Float() = subID.get();
  196. }
  197. std::string oldMeta = config.meta; // FIXME: move into inheritNode?
  198. JsonUtils::inherit(config, objects.at(ID)->base);
  199. config.setMeta(oldMeta);
  200. loadObjectEntry(identifier, config, objects[ID]);
  201. }
  202. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  203. {
  204. assert(objects.count(ID));
  205. assert(objects.at(ID)->subObjects.count(subID));
  206. objects.at(ID)->subObjects.erase(subID); //TODO: cleanup string id map
  207. }
  208. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  209. {
  210. return std::vector<bool>(); //TODO?
  211. }
  212. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  213. {
  214. if (objects.count(type))
  215. {
  216. if (objects.at(type)->subObjects.count(subtype))
  217. return objects.at(type)->subObjects.at(subtype);
  218. }
  219. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  220. throw std::runtime_error("Object type handler not found");
  221. return nullptr;
  222. }
  223. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(std::string type, std::string subtype) const
  224. {
  225. boost::optional<si32> id = VLC->modh->identifiers.getIdentifier("core", "object", type, false);
  226. if(id)
  227. {
  228. si32 subId = objects.at(id.get())->subIds.at(subtype);
  229. return objects.at(id.get())->subObjects.at(subId);
  230. }
  231. logGlobal->errorStream() << "Failed to find object of type " << type << ":" << subtype;
  232. throw std::runtime_error("Object type handler not found");
  233. return nullptr;
  234. }
  235. std::set<si32> CObjectClassesHandler::knownObjects() const
  236. {
  237. std::set<si32> ret;
  238. for (auto entry : objects)
  239. ret.insert(entry.first);
  240. return ret;
  241. }
  242. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  243. {
  244. std::set<si32> ret;
  245. if (objects.count(primaryID))
  246. {
  247. for (auto entry : objects.at(primaryID)->subObjects)
  248. ret.insert(entry.first);
  249. }
  250. return ret;
  251. }
  252. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  253. {
  254. for (auto & entry : object["types"].Struct())
  255. {
  256. JsonUtils::inherit(entry.second, object["base"]);
  257. for (auto & templ : entry.second["templates"].Struct())
  258. {
  259. JsonUtils::inherit(templ.second, entry.second["base"]);
  260. }
  261. }
  262. }
  263. void CObjectClassesHandler::afterLoadFinalization()
  264. {
  265. for (auto entry : objects)
  266. {
  267. for (auto obj : entry.second->subObjects)
  268. {
  269. obj.second->afterLoadFinalization();
  270. if (obj.second->getTemplates().empty())
  271. logGlobal->warnStream() << "No templates found for " << entry.first << ":" << obj.first;
  272. }
  273. }
  274. }
  275. std::string CObjectClassesHandler::getObjectName(si32 type) const
  276. {
  277. if (objects.count(type))
  278. return objects.at(type)->name;
  279. logGlobal->errorStream() << "Access to non existing object of type " << type;
  280. return "";
  281. }
  282. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  283. {
  284. if (knownSubObjects(type).count(subtype))
  285. {
  286. auto name = getHandlerFor(type, subtype)->getCustomName();
  287. if (name)
  288. return name.get();
  289. }
  290. return getObjectName(type);
  291. }
  292. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  293. {
  294. return objects.at(type)->handlerName;
  295. }
  296. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  297. {
  298. this->type = type;
  299. this->subtype = subtype;
  300. }
  301. void AObjectTypeHandler::setTypeName(std::string type, std::string subtype)
  302. {
  303. this->typeName = type;
  304. this->subTypeName = subtype;
  305. }
  306. static ui32 loadJsonOrMax(const JsonNode & input)
  307. {
  308. if (input.isNull())
  309. return std::numeric_limits<ui32>::max();
  310. else
  311. return input.Float();
  312. }
  313. void AObjectTypeHandler::init(const JsonNode & input, boost::optional<std::string> name)
  314. {
  315. base = input["base"];
  316. if (!input["rmg"].isNull())
  317. {
  318. rmgInfo.value = input["rmg"]["value"].Float();
  319. rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]);
  320. rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
  321. rmgInfo.rarity = input["rmg"]["rarity"].Float();
  322. } // else block is not needed - set in constructor
  323. for (auto entry : input["templates"].Struct())
  324. {
  325. entry.second.setType(JsonNode::DATA_STRUCT);
  326. JsonUtils::inherit(entry.second, base);
  327. ObjectTemplate tmpl;
  328. tmpl.id = Obj(type);
  329. tmpl.subid = subtype;
  330. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  331. tmpl.readJson(entry.second);
  332. templates.push_back(tmpl);
  333. }
  334. if (input["name"].isNull())
  335. objectName = name;
  336. else
  337. objectName.reset(input["name"].String());
  338. initTypeData(input);
  339. }
  340. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  341. {
  342. return false; // by default there are no overrides
  343. }
  344. void AObjectTypeHandler::preInitObject(CGObjectInstance * obj) const
  345. {
  346. obj->ID = Obj(type);
  347. obj->subID = subtype;
  348. obj->typeName = typeName;
  349. obj->subTypeName = subTypeName;
  350. }
  351. void AObjectTypeHandler::initTypeData(const JsonNode & input)
  352. {
  353. // empty implementation for overrides
  354. }
  355. boost::optional<std::string> AObjectTypeHandler::getCustomName() const
  356. {
  357. return objectName;
  358. }
  359. void AObjectTypeHandler::addTemplate(ObjectTemplate templ)
  360. {
  361. templ.id = Obj(type);
  362. templ.subid = subtype;
  363. templates.push_back(templ);
  364. }
  365. void AObjectTypeHandler::addTemplate(JsonNode config)
  366. {
  367. config.setType(JsonNode::DATA_STRUCT); // ensure that input is not null
  368. JsonUtils::inherit(config, base);
  369. ObjectTemplate tmpl;
  370. tmpl.id = Obj(type);
  371. tmpl.subid = subtype;
  372. tmpl.stringID = ""; // TODO?
  373. tmpl.readJson(config);
  374. addTemplate(tmpl);
  375. }
  376. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  377. {
  378. return templates;
  379. }
  380. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  381. {
  382. std::vector<ObjectTemplate> templates = getTemplates();
  383. std::vector<ObjectTemplate> filtered;
  384. std::copy_if(templates.begin(), templates.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  385. {
  386. return obj.canBePlacedAt(ETerrainType(terrainType));
  387. });
  388. // H3 defines allowed terrains in a weird way - artifacts, monsters and resources have faulty masks here
  389. // Perhaps we should re-define faulty templates and remove this workaround (already done for resources)
  390. if (type == Obj::ARTIFACT || type == Obj::MONSTER)
  391. return templates;
  392. else
  393. return filtered;
  394. }
  395. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  396. {
  397. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  398. for (auto & tmpl : ret)
  399. {
  400. if (objectFilter(object, tmpl))
  401. return tmpl;
  402. }
  403. return boost::optional<ObjectTemplate>();
  404. }
  405. const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
  406. {
  407. return rmgInfo;
  408. }
  409. bool AObjectTypeHandler::isStaticObject()
  410. {
  411. return false; // most of classes are not static
  412. }
  413. void AObjectTypeHandler::afterLoadFinalization()
  414. {
  415. }